Arrow functions do not have their own âthisâ binding so there is no way that you can refer to âkey2â since âthisâ does not bind to the the obj2 object when using the arrow function.
Quiz: If âthisâ is not binding to obj2 then what is it binding to?
Ok, that makes sense. I learned from this next test that objects do not generate their own (bindable) context. You need an ES5 function. Otherwise (to answer your question) this binds to the global object or undefined in normal/strict mode.
const obj3 = {
key2 : [1,2,3],
method : this.key2.forEach(() => console.log(this)) // this is undefined here too
}
obj3.method();
I have a followup question. The first log statement below suggests that objects do not create contexts. This is confirmed by the 2nd log statement that reiterates what has been said about arrow functions also not creating a context, and thus reaching outwards for one (global object here).
The 3rd log statement, however, does not show method outer as the context of this. It shows the entire object!
How can this be? Didnât we disqualify obj as a context of its own from the prior two log statements?
My best guess is that the method outerFunc converts obj into its context at runtime. And this context is detroyed after the method invocation completes. Is that correct?
The way you are defining outerFunc creates a closure:
The closure consists of the outer scope (or the âparent scopeâ) of the function. So outerFunc has access to all of the variables/methods in obj and âthisâ points to the closure. Thatâs why you would be able to access this.key1 inside of outerFunc if you wanted to (and thatâs why innerArrowFunction returns an object, because the object is outerFuncâs parent scope).
Yes, the closure is created at runtime when outerFunc is invoked.