I have a simple prototype chain, and I want to get the name of all prototypes that are a part of it:
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);
}
I would expect to get Cat
, then Animal
, then Object
. However, I am getting:
Animal
Animal
Animal
Object
Can someone explain to me why this happens, and how to get the correct result. Is my whole prototype inheritance wrong..?
When you did Cat.prototype = new Animal();
, you made
[[prototype]]
of Child be a ref to Parent
.
This changes the child's constructor pointing to parent.
you need to explicitly set
Cat.prototype.constructor = Cat;
See the below example:
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);
}