原型的重写的问题

1:弊端 无法通过构造函数来设置属性值

           当属性中有引用变量类型时,可能存在变量值重复

 

function Person(){

}

Person.prototype = {

constructor:Person,

name:"Amos",

age=22,

friends:["eclipse","tomcat"],

say:function(){

alert(this.name+"\t"+this.friends);

}

}

var p1 = new Person();

p1.name="aa";

p1.say(); // aa [eclipse,tomcat];

var p2 = new Person();

p2.say(); //Amos[ecplise.tomcat]

但是如果在p1.friends.fush("new friend") //会在原型中找friends(自己本身是没有这个属性的)。所以新的朋友会加到原型中。但是如果是p1.friends = ["new friend"];

这样就会直接加到自己的对象空间中。

var p1 = new Person();

p1.friends.push("new friend");

p1.say();// Amos eclise,tomcat,new friend

var p2 = new Person();

p2.say(); amos ecplise,tomcat,new friend

 

但是如果:

p1.friends = ["new friend"];

p1.say(); //  Amos new friend

p2.say(); // Amos eclipse tomcat

 

 

 

 

posted on 2013-07-02 09:51  菜鸟半只  阅读(176)  评论(0)    收藏  举报

导航