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

175
Visualizações
this inside arrow functions in JavaScript

I have this following class...

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    getName() {
        return this.name;
    }

    getAge = () => this.age;
};

I know that when class or object methods are passed to other places, they lose this. So when I assign p1.getName method to another global variable printName, the value of this inside printName will be undefined and it will give me an error because of this.name. (Please see the example below) This happens because the context is changed. Is my understanding correct?

let p1 = new Person('John', 20);
let printName = p1.getName;
console.log(printName()); // Cannot read properties of undefined (reading 'name')

So what about the one with arrow function? In Person class, getAge is a class field which has an arrow function expression. When I pass p1.getAge to somewhere else, this still references the right object.

let printAge = p1.getAge;
console.log(printAge());  // 20

When I pass p1.getAge method to global variable called printAge, the context is changed. Am I right? I also know the fact that, arrow functions capture this from its outer lexical scope. Based on my understanding, this shouldn't be p1 object.

I know how to bind object methods. But I just want to know why does this inside arrow function still refer to the right object? What am I missing? Or my already understandings are wrong?

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