Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

78
Visualizações
Can someone help me to sort out why in the current scenario this behave like this

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
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda