代码1:function rectangle(w,h){
this.width = w ;
this.height = h ;
this.area = function(){
return this.height * this.width
}
}代码2:function rectangle(w,h){
this.width = w ;
this.height = h ;
}
rectangle.prototype.area = function(){
return this.height * this.width
}请问代码1与代码2设置area熟悉的时候,两种方法有什么区别么? 为什么有的时候用prototype来设置有的时候却在函数里面设置啊?
this.width = w ;
this.height = h ;
this.area = function(){
return this.height * this.width
}
}代码2:function rectangle(w,h){
this.width = w ;
this.height = h ;
}
rectangle.prototype.area = function(){
return this.height * this.width
}请问代码1与代码2设置area熟悉的时候,两种方法有什么区别么? 为什么有的时候用prototype来设置有的时候却在函数里面设置啊?
代码1.每次实例化都要重新生成一个新的area方法.白白浪费内存.
代码2.直接是原型链引用area.是共享的.所以每次实例化只实例化属性.而方法是共享的.所以基本上 属性是放在构造器里.因为每次实例化需要动态改变属性. 而prototype里放方法.因为方法通常
是不变的 所以共享即可
var r2= new rectangle(20,20);
alert(r1.area == r2.area);//第一种是false,第二种是trueLZ可以看到,第一种两个实例的area方法并不指向同一块内存区域,也就是实际上内存是单独分配的,而实际上area要完成的功能都是一样的,这样就造成了内存的浪费,如果函数体很大,实例化的越多,那么消耗就越多,而第二种就避免了这个问题,当函数执行时,会先查找当前实例有无此方法,如果找不到就去他的prototype中查找,如果还没有,就再次向上级的prototype中查找,是一个链式的查找方式,直到找到该方法就返回,或者找到Object.prototype还没有找到,那么就是undefined。另外,一下两个函数LZ可以看看他们是做什么用的。/*function rectangle(w,h){
this.width = w ;
this.height = h ;
this.area = function(){
return this.height * this.width
}
}*/function rectangle(w,h){
this.width = w ;
this.height = h ;
}
rectangle.prototype.area = function(){
return this.height * this.width
}var r1 = new rectangle(10,10);
alert(r1.hasOwnProperty('area'));
alert(rectangle.prototype.isPrototypeOf(r1));
代码2.直接是原型链引用area.是共享的.所以每次实例化只实例化属性.而方法是共享的.所以基本上 属性是放在构造器里.因为每次实例化需要动态改变属性. 而prototype里放方法.因为方法通常
是不变的 所以共享即可
……
[/Quote]