3 ms·
> So do you agree with [goto11 that] ""this" has lexical scope just like regular parameters" and "Nevertheless, scope wise it behaves like an implicit paramete
by minitech 7y ago
> So do you agree with [goto11 that] ""this" has lexical scope just like regular parameters" and "Nevertheless, scope wise it behaves like an implicit parameter with lexical scope"?
Yes.
> Explain just how "this" is lexically scoped, what "lexically scoped" means, and then explain why they had to add fat arrow to the language, if "this" is "just like regular parameters", please?
`this` is lexically scoped* because the function it belongs to is determined by where it appears in the code.
Fat arrow was added to the language with this difference because it’s useful to have a function without its own `this`.
> If "this" is lexically scoped, then why can call and apply change it at runtime?
It’s always set at call time. Not a matter of scope. (Parameters: also have values determined at call time, also lexically scoped.)
function a() { return this; }
let obj = {a};
obj.a() === obj
> And how do explain this stackexchange discussion, which directly addresses and answers the question? The detailed answer "yes" got five votes and was accepted. The other answer "no" got one vote and was not accepted. What's your answer?
The answer is wrong despite its votes. The comment on it by JacquesB is correct: “This is confusing values and variables. this cares cares how a function is called the same way parameters care how a function is called - they get their value at runtime when the function is called. But the scope of all variables (including this) is lexical and not dynamic.”
> Whatever you call it and however you define dynamic scope, the dynamic way "this" behaves IS terrible, and undeniably causes lots of easy to make, hard to diagnose bugs. That is why Brendan Eich called it a "footgun". That was my point, and that was why they had to add fat arrow to the language.
I disagree, but am mostly here to argue against objectively wrong information rather than opinions.
* in contrast to dynamically scoped. In JavaScript it’s also common to use “lexical scope” in contrast to “function scope” to distinguish `let`/`const` vs. `var`. In the JavaScript spec, the lexical thisMode refers to where the (arrow) function appears, not the position of the `this`.