I'm experiencing a major brain freeze here understanding arrow functions and lexical scope: I read through all of Kyle Simpson's 'You don't know JS' some time ago, and I thought I understood scope and context pretty well. But I'm just not understanding how arrow function lexical scope applies to objects -- I've been working with classes in React, and there it's always clear that the this that the arrow function bound to was the class.
For instance, in this example (from https://medium.com/tfogo/advantages-and-pitfalls-of-arrow-functions-a16f0835799e)
let obj = {
myVar: 'foo',
myFunc: function() {
console.log(this.myVar)
setTimeout(() => {
console.log(this.myVar)
}, 1000)
}
}
The arrow function should bind this correctly, obviating doing a bind. But this is from lexical scope? In what sense? Because the next scope is that of the function myFunc and this function's lexical parent scope is obj?
But then they give this example
let obj = {
myVar: 'foo',
myFunc: () => {
console.log(this.myVar)
}
}
obj.myFunc() // undefined
where correct binding of this does not happen. Is this because there is no function surrounding the arrow function, and so the next lexical scope is the global context?
To sum it up: is it true that the 'lexical scope' here is simply that same lexical scope defined by functions, and that this with arrow functions is simply to look for the parent of the next containing function?
I promise you I understood this (or thought I did) a while ago, but 'use it or lose it', I guess --