Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

171
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda