I'm hitting a bit of a wall understanding the this keyword's behavior, specifically when dealing with arrow functions versus regular functions within object methods. I thought I had a handle on it, but a recent piece of code has me scratching my head.
Consider this simplified example:
Code : Tout sélectionner
const myObject = {
data: 'Hello',
regularFunction: function() {
console.log(this.data);
},
arrowFunction: () => {
console.log(this.data);
},
nestedObject: {
data: 'World',
regularNested: function() {
console.log(this.data);
},
arrowNested: () => {
console.log(this.data);
}
}
};
myObject.regularFunction();
myObject.arrowFunction();
myObject.nestedObject.regularNested();
myObject.nestedObject.arrowNested();
And then, how does that apply to the nestedObject? In regularNested, this correctly refers to nestedObject. But arrowNested also prints undefined (or global this.data).
My understanding was that arrow functions don't have their own this context and instead inherit it from their surrounding lexical scope. So, I'd expect arrowFunction to inherit this from the object literal context (which should be myObject), and arrowNested to inherit from nestedObject. Clearly, I'm missing something fundamental about the "lexical scope" rule in this specific scenario.
golf hit
Can anyone help clarify why this behaves this way for arrow functions when they are direct methods of an object or a nested object, and how their lexical this is determined in such cases?
Thanks in advance for any insights!