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

javascript类继承采用动态原型法的错误分析
function Person (name){
this.name = name;
if(typeof Person._initialized=="undefined"){
Person.prototype.say = function (){
alert(this.name);
};
Person._initialized = true;
}
}

function WhitePerson (name){
Person.call(this,name);
this.name = name;
if(typeof WhitePerson._initialized=="undefined"){
//WhitePerson.prototype = new Person();
WhitePerson.prototype.area  = function (){
alert("中国"+this.name);
};
WhitePerson._initialized  =true;
}
}

动态原型继承方式采用的是对象冒充(this的特点)来继承构造函数的属性,
而用原型链继承prototype对象的方法。

function WhitePerson (name){
Person.call(this,name);   //对象冒充继承了person的属性
this.name = name;
if(typeof WhitePerson._initialized=="undefined"){
WhitePerson.prototype.area  = function (){  //新的prototype属性
alert("中国"+this.name);
};
WhitePerson._initialized  =true;
}
发现没?你一直没有继承基类person的prototype属性,
也就是你并没有继承Person.prototype.say = function (){
alert(this.name);
}
所以应当加上这一句
WhitePerson.prototype = new Person ();
这里有一点要注意,这一句要写在函数的外面,就是:
function WhitePerson (name){
...省略
WhitePerson.prototype.area  = function (){
alert("中国"+this.name);
};
WhitePerson._initialized  =true;
}
}
WhitePerson.prototype = new Person ();


如果写在函数内部
……省略
WhitePerson.prototype = new Person ();
WhitePerson.prototype.area  = function (){
alert("中国"+this.name);
};
WhitePerson._initialized  =true;
}
}
则会因为对象因为被提前实例化而导致后面的 area方法失效

用动态原型方法来构造函数的好处就是更加像一个类,但是如果用来继承,
则因为实例化要在函数结束后进行,因此就失去了这个方法的本意,还增加了代码量。
因此我个人不喜欢用这种方法。