我有一个简单的原型链,我想得到所有原型的名称:
function Animal(name, age){
this.name = name;
this.age = age;
this.eat = function(){console.log(name + " eats");}
this.getAge = function(){console.log(name + " is " + age + " years old");}
}
function Cat(name, age){
Animal.call(this, name, age);
this.hunt = function(){console.log(name + " hunts mice")};
}
Cat.prototype = new Animal();
var cat1 = new Cat("cat1", 2);
var currentPrototype = cat1;
while(currentPrototype != null){
console.log(currentPrototype.constructor.name);
currentPrototype = Object.getPrototypeOf(currentPrototype);
}
我希望得到Cat
,然后是Animal
,然后是Object
。但是,我得到了:
Animal
Animal
Animal
Object
有人可以向我解释为什么会发生这种情况,以及如何获得正确的结果。我的整个原型继承是错误的吗?
答案 0 :(得分:0)
当你Cat.prototype = new Animal();
时,你做了
[[prototype]]
是Parent
的参考。
这会更改指向父级的子构造函数。
您需要明确设置
Cat.prototype.constructor = Cat;
见下面的例子:
function Animal(name, age){
this.name = name;
this.age = age;
this.eat = function(){console.log(name + " eats");}
this.getAge = function(){console.log(name + " is " + age + " years old");}
}
function Cat(name, age){
Animal.call(this, name, age);
this.hunt = function(){console.log(name + " hunts mice")};
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat1 = new Cat("cat1", 2);
var currentPrototype = cat1;
while(currentPrototype != null){
console.log(currentPrototype.constructor.name);
currentPrototype = Object.getPrototypeOf(currentPrototype);
}