Reputation: 1590
I am learning NodeJS and learning prototypal inheritance.
Below is the code I am using for prototypal inheritance .
The issue I am facing is :
The meow, purr and hiss
methods do get called on leopardObj
.
But , whenever I call below methods , inside those methods , this.name
is always coming as undefined.
leopardObj.meow();
leopardObj.purr();
leopardObj.hiss();
Can anybody please help me as I am not able to understand why this.name
is coming as undefined ?
function Cat(name){
console.log("Inside Cat before = ",name);
this.name = name
console.log("Inside Cat after = ",this.name);
}
Cat.prototype.meow = () => {
console.log(this);
console.log("Meow for !!",this.name);
}
function Lynx(name){
console.log("Inside Lynx with name = ",name);
Cat.call(this,name);
}
Lynx.prototype = Object.create(Cat.prototype);
Lynx.prototype.purr = () => {
console.log("Purr for !! ",this.name);
}
function Leopard(name){
console.log("Inside Leopard with name = ",name);
Lynx.call(this,name);
}
Leopard.prototype = Object.create(Lynx.prototype);
Leopard.prototype.hiss = () => {
console.log("Hiss for !! ",this.name);
}
const leopardObj = new Leopard("Sheryl");
leopardObj.meow();
leopardObj.purr();
leopardObj.hiss();
Upvotes: 0
Views: 62
Reputation: 685
meow
, purr
and hiss
functions are arrow functions, so you have bind your context incorrectly. Change them to regular functions back and everything will work as expected:
Leopard.prototype.hiss = function() {
console.log("Hiss for !! ", this.name);
}
Upvotes: 1