Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!