日期:2014-05-16  浏览次数:20332 次

js中组合使用构造函数模式和原型模式创建对象

 

js中组合构造函数模式和原型模式创建对象是最常见的方法。

构造函数模式用于定义实例属性,原型模式用于定义方法和共享属性。优点如下

①每个实例都会有自己的一份实例属性的副本,又同时共享对方法的引用,最大限度地节省了内存。
②这种混合模式还支持向构造函数传递参数。


function Student(name,age,class){
 this.name = name;
 this.age = age;
 this.class = class;
 this.friends = ["Tom","Lily"];
}

Student.prototype = {
 constructor:Student,
 sayName : function(){
  alert(this.name);
 }
}

var s1 = new Student("xy1",23,"classA");
s1.friends.push("Jerry");

var s2 = new Student("xy2",23,"classB");

alert(s1.friends);
结果"Tom,Lily,Jerry";

alert(s2.friends);
结果"Tom,Lily"

alert(s1.friends == s2.friends);
结果false

alert(s1.sayName == s2.sayName);
结果false

 

这种方式创建对象,是目前使用最广泛,认同度最高的一种方式。甚至可以书是一种默认的模式。