Skip to content

Instantly share code, notes, and snippets.

@laispace
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laispace/b0e702efcd1e6abac702 to your computer and use it in GitHub Desktop.
Save laispace/b0e702efcd1e6abac702 to your computer and use it in GitHub Desktop.
设计模式-原型模式
// 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);
@laispace
Copy link
Author

laispace commented Feb 8, 2015

另一种方式

function Person (name, age) {
    this.name = name;
    this.age = age;
}

function SuperHero (name, age, powers) {
    // superhero is a normal person first
    Person.call(this, name, age);

    // then he has super powers!
    this.powers = powers;
}

// now we create a super hero
var superhero = new SuperHero ('xiaolai', 18, ['eat', 'sleep']);
console.log(superhero);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment