Why does this behaves so weird (my understanding is wrong may be ;() . In the below code i have taken two scenario -> 1) am trying to add the entire personPrototype Object as a prototype of Person and 2) am trying to add a specific method of personPrototype (greet method) to the prototype of Person.
In both cases am getting value of this keyword differently why is it so ? can someone help me out. I have added both scenario in the below code and commented out my result as well.Am really interested to know is work of this keyword in current scenario and not the fix.
const personPrototype = {
greet() {
console.log(this)
console.log(`hello, my name is ${this.name}!`);
}
}
function Person(name) {
this.name = name;
}
var p1=new Person("Sam")
Person.prototype.test=personPrototype.greet;
console.log(p1.test()) //prints Sam //this in greet method is Person obj
Person.prototype.test=personPrototype;
console.log(p1.test.greet()) //prints undefined //this in greet method is greet obj