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

来源:互联网 发布:java的原始数据类型 编辑:程序博客网 时间:2024/05/16 05:09

组合使用构造函数模式和原型模式:


创建自定义类型的最常见方式,就是组合使用构造函数模式与原型模式。构造函


数模式用于定义实例属性,而原型模式用于定义方法和共享的属性,这样就使得每


个实例都会有自己的一份实例属性的副本,但同时又会共享着对方法的引用,最大


限度地节省了内存,而且这种模式还支持想构造函数传递参数


例1:

function Person(name,age){
this.name=name;
this.age=age;
this.friends=["Icarid","Chris"];
}


Person.prototype={
constructor:Person,//constructor是保存对函数对象的指针
getName:function(){
alert(this.name)
}
}


var person1=new Person("Joe",23);
var person2=new Person("Leo",35);


person1.getName();//Joe
person2.getName();//Leo


alert(person1.getName==person2.getName);//true,说明两个实例的方法的指针相同


alert(person1.friends);//Icarid,Chris
person1.friends.push("John");//向数组中传递参数,添加到数组末尾
alert(person1.friends);//Icarid,Chris,John

 alert(person2.friends);//Icarid,Chris,说明实例的属性都是分开的,即互不影响



使用构造函数与原型混合的模式,是ECMAScript中使用最广泛,认同度最高的一种创建自定义


类型的方法。

阅读全文
0 0
原创粉丝点击