var person1 = new Person("lisi",21,["lida","lier","wangwu"]); console.log(person1); var person2 = new Person("wangwu",21,["lida","lier","lisi"]); console.log(person2);
可以看出,混合模式共享着对相同方法的引用,又保证了每个实例有自己的私有属性。最大限度的节省了内存。
1、new Object
1 2 3 4 5 6 7
var person = new Object(); person.name = "lisi"; person.age = 21; person.family = ["lida","lier","wangwu"]; person.say = function(){ alert(this.name); }
2、字面量
1 2 3 4 5 6 7 8
var person ={ name: "lisi", age: 21, family: ["lida","lier","wangwu"], say: function(){ alert(this.name); } };
以上两种方法在使用同一接口创建多个对象时,会产生大量重复代码,为了解决此问题,工厂模式被开发。
3、工厂模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14
function createPerson(name,age,family) { var o = new Object(); o.name = name; o.age = age; o.family = family; o.say = function(){ alert(this.name); } return o; }
var person1 = createPerson("lisi",21,["lida","lier","wangwu"]); //instanceof无法判断它是谁的实例,只能判断他是对象,构造函数都可以判断出 var person2 = createPerson("wangwu",18,["lida","lier","lisi"]); console.log(person1 instanceof Object); //true
var person1 = new Person("lisi",21,["lida","lier","wangwu"]); console.log(person1); var person2 = new Person("wangwu",21,["lida","lier","lisi"]); console.log(person2);
可以看出,混合模式共享着对相同方法的引用,又保证了每个实例有自己的私有属性。最大限度的节省了内存。
感觉最常用的是6混合模式。
此外,高程中还提到了动态原型模式,寄生构造函数模式,稳妥构造函数模式。
7、动态原型模式
1 2 3 4 5 6 7 8 9
function Person(name) { this.name = name; if (typeof this.getName != "function") { Person.prototype.getName = function () { console.log(this.name); } } } var person1 = new Person();