use cases for arrow functions inheriting their this value
Hey, mdn says that the
this
value of arrow functions equates to the parent scope, i don't understand how that could be useful? For example, if i defined an arrow function in an object below that utilized the this
keyword, how would i benefit from it being equal to the window object? (i'm aware if i want that behaviour then to use a regular function of course but the concept confuses me)
i'd appreciate any help. thanks in advance.8 Replies
You are looking at it from the wrong perspective. Referring to the window object is a consequence of how things work rather than a goal set forth by the designers. The proper way to think about it is that arrow functions don't have a "this" binding of their own. For any regular identifier, like a variable name, if it's not defined in the local scope, outer scopes are searched until a match is found. The same is happening with "this". It's not defined in the arrow function, but there is one in some outer scope, so the one in the closest outer scope is used. The window is an object and it's the outermost object, so that is what "this" refers to if there is nothing else for it to point to. Also note that window is only the outermost scope in the front end. In the back end, it could be module or globalThis, depending on if the code is run in a module or not.
Ahh okay that makes more sense. So for regular functions is it safe to assume that the
this
value is always what object itβs located in since it can bind its own?No. It depends on how the function is called. It doesn't always bind to the object that it is in.
Oh so for example if you pass a function into another via a callback parameter it would lose its
this
value right? Thatβs the sort of thing you mean by βdepends how itβs calledβ?Ah yeah the
external
example is what I meant by the callback example, I should have said βfunction being referenced in a variable` or something. But I see now yeah. I appreciate the helpI just realized that I should have renamed it because it's not an arrow function anymore, but that wasn't the main point. I used your code as the starter for simplicity.
Ah yeah no worries, I got what you meant