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?