1.组合模式
组合使用构造函数模式和原型模式。
构造函数用于定义实例属性,原型模式用于定义方法和共享属性。这种模式是目前在ECMAScript中使用最广泛,认同度最高的一种创建自定义类型的方法。
function Person(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
this.firends = ['lisi','huangzhu'];
}
Person.prototype = {
constructor: Person,
sayName: function(){
console.log(this.name);
}
};
var p1 = new Person('wanlao',19,'male');
var p2 = new Person('kuanhuang',18,'male');
p1.firends.push('kunzhu');
console.log(p1.firends); //['lisi','huangzhu','kunzhu']
console.log(p2.firends); //['lisi','huangzhu']
console.log(p1.firend === p2.firend); //false
console.log(p1.sayName === p2.sayName); //true
构造函数里填写实例的属性,原型模式填写共享属性和方法。