0

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?

  • 1
    "*I also know the fact that, arrow functions capture this from its outer lexical scope.*" this is correct but the next sentence contradicts it: "*Based on my understanding, this shouldn't be p1 object.*" why wouldn't it be `p1`? – VLAZ Sep 15 '21 at 08:21
  • Because the context is changed and ```printAge``` is in global scope. Am I right? – Enthalpy127 Sep 15 '21 at 08:22
  • 2
    No, arrow functions use the `this` from the lexical context *at creation time*. Reassigning them doesn't change that. In fact, that was a design goal behind them. – VLAZ Sep 15 '21 at 08:23
  • your class has a method called getName when you call this method in the second code block: let printName = p1.getName; You're not calling it as a method hence it doesn't return anything. If you did let printName = p1.getName(); it would return the value. when you do this you'll see that printAge is not a function but you're calling it with console.log(printAge()) as if it is one. – Jarne Kompier Sep 15 '21 at 08:23
  • @VLAZ Oh, so I am missing the fact that 'this' is never changed when they are inside arrow functions. Thanks man. – Enthalpy127 Sep 15 '21 at 08:26
  • Out of curiosity why would you want to do `let printName = p1.getName;` anyway? – Andy Sep 15 '21 at 08:27
  • Guys, I just want to know what will happen when I move object methods to other places. I am not calling methods directly from ```p1``` object. – Enthalpy127 Sep 15 '21 at 08:29

0 Answers0