Confused about this keyword behavior in arrow functions vs. regular functions within objects
Posté : 23 juin 2025, 12:49
Hey everyone,
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:
I understand that in regularFunction, this refers to myObject. But for arrowFunction, why does this.data usually print undefined (or something from the global context like window.data in a browser environment) rather than myObject.data?
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!
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!