Last active
August 29, 2015 14:14
-
-
Save laispace/b0e702efcd1e6abac702 to your computer and use it in GitHub Desktop.
设计模式-原型模式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pattern-prototype.js | |
// ===== 1. use Object.create ===== | |
var person = { | |
nation: 'china', | |
say: function (something) { | |
console.log(this.name, 'says: ', something); | |
} | |
}; | |
// use Object.create to create a new person | |
var newPerson = Object.create(person, { | |
'name': { | |
value: 'xiaolai-1', | |
enumerable: true | |
}, | |
'age': { | |
value: 11, | |
enumerable: true | |
}, | |
'salary': { | |
value: 11111, | |
enumerable: true | |
} | |
}); | |
// say hi | |
newPerson.say('hi'); | |
// get salary | |
var salary = newPerson.salary; | |
console.log(salary); | |
// ===== 2. use empty function ===== | |
var prototype = { | |
nation: 'china', | |
say: function (something) { | |
console.log(this.name, 'says: ', something); | |
} | |
}; | |
function Person (opts) { | |
function emptyFunction () {} | |
emptyFunction.prototype = prototype; | |
var person = new emptyFunction(opts); | |
person.name = opts.name; | |
person.age = opts.age; | |
person.salary = opts.salary; | |
return person; | |
} | |
var newPerson = Person({ | |
name: 'xiaolai-2', | |
age: 22, | |
salary: 22222 | |
}); | |
// say hello | |
newPerson.say('hello'); | |
// get salary | |
var salary = newPerson.salary; | |
console.log(salary); | |
// ===== 3. the other way to use empty function ===== | |
var Person = (function () { | |
var emptyFunction = function () {}; | |
return function (opts) { | |
emptyFunction.prototype = opts; | |
var person = new emptyFunction(); | |
return person; | |
} | |
})(); | |
var newPerson = Person({ | |
nation: 'china', | |
name: 'xiaolai-3', | |
age: 33, | |
salary: 33333, | |
say: function (something) { | |
console.log(this.name, 'says: ', something); | |
} | |
}); | |
// say halo | |
newPerson.say('hola'); | |
// get salary | |
var salary = newPerson.salary; | |
console.log(salary); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
另一种方式