当前位置: 代码迷 >> Web前端 >> prototype模式继承
  详细解决方案

prototype模式继承

热度:163   发布时间:2012-10-28 09:54:44.0
prototype方式继承
javascript的继承和java不同,不是基于class实现,而是基于prototype实现的。
function Animal(nAge){
    this.age = nAge;
}
Animal.prototype.eat = function(){
    // eat something
};
function Cat(sName){
    this.name = sName;
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat = new Cat("kitty");
cat.eat();

其中
Cat.prototype.constructor = Cat;

这行代码的作用是:
默认情况下,Cat.prototype.constructor是Cat。但是为了使Cat继承Animal,设置了
Cat.prototype = new Animal();

将Cat.prototype设置为Animal的一个实例。于是这个时候Cat.prototype.constructor就成了Animal实例的constructor,即Animal.prototype.constructor,也就是Animal。所以为了不丢失cat的构造函数,需要手工设置
Cat.prototype.constructor = Cat;

使构造函数指向Cat。在javascript中使用继承时,要务必注意这一点。任何情况下如果给Cat.prototype赋值了,比如
Cat.prototype = {};

那么接下来一定要手工设置Cat.prototype.constructor的值。
  相关解决方案