Monday, May 20, 2024
10
rated 0 times [  13] [ 3]  / answers: 1 / hits: 15710  / 7 Years ago, sat, may 20, 2017, 12:00:00

I thought I understood the relationship between this and arrow functions but the following snippet is making me question my understanding.



let person = {
name: 'Jim',
sayName: () => {
console.log(this.name);
}
};

person.sayName();


I understand that arrow functions capture the this value of the enclosing context. I was expecting this would be the object but instead it is Window.



Can someone help me understand why this is the case?


More From » ecmascript-6

 Answers
3

Your understanding of arrow functions is mostly correct: Arrow functions have a lexical this and its value within the arrow function is determined by the surrounding scope.



You probably assume that this gets a different value within the person object literal. This is not the case.



So let's see what this refers to in your (global) scope:





console.log(this === window); // true

let person = {
name: 'Jim',
test: console.log(this === window), // true
sayName: () => {
console.log(this === window); // true
}
};

person.sayName();





As you can see, when the arrow function assigned to sayName is created, this refers to the window object.


[#57718] Thursday, May 18, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
finn

Total Points: 154
Total Questions: 88
Total Answers: 82

Location: Lithuania
Member since Mon, Nov 16, 2020
4 Years ago
;