0

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
  • `p1.test.greet()` means the `this` inside refers to `p1.test`, which doesn't have a `name` – CertainPerformance Mar 28 '22 at 18:25
  • Friendly advice: Write more descriptive questions. When I'm skimming the list of questions and see this, I have no idea whether I'm the person to answer it or not, so I probably won't bother looking. Part of the problem is that when you wrote "this" it wasn't clear that you meant the javascript keyword `this`. – David Knipe Mar 28 '22 at 18:54
  • @DavidKnipe Sure. thanks for the advice.would look into it while posting it next time – Sreejith Narayanankutty Mar 28 '22 at 20:00

0 Answers0