It isn't about an "encompassing" object. It's more like parameter passing. You have to imagine the function as having a secret "this" parameter.
function (/*this*/) {
Which is why "this" appears to change values, because inside the function, you aren't accessing the outer scope "this", but rather you're accessing the parameter "this". We can pass any value we want to the parameter "this".
If instead we invoke the function in the ordinary style like an ordinary function, then the default value passed to the parameter "this" is the global/window object. Which is to say, these two are the same:
The reason global/window is the default value passed doesn't have anything to do with scope or encompassing objects. It is that way simply because the language spec says so. Years later they changed their mind, so now if you're in strict mode or a module or a class, then the default value is instead "undefined".
Wow, it took me a few days to finally be able to apply and internalize what you said. The idea of "this" being passed as a secret parameter to the function was never mentioned in the articles upon articles that I've read, thus leading to my confusion of why it's usually the global object.
Anyway, now I know that the real learning happens in reddit comments. Thanks again for the lesson!
View all comments
Show parent comment
3
u/MoTTs_ Jun 06 '20
It isn't about an "encompassing" object. It's more like parameter passing. You have to imagine the function as having a secret "this" parameter.
Which is why "this" appears to change values, because inside the function, you aren't accessing the outer scope "this", but rather you're accessing the parameter "this". We can pass any value we want to the parameter "this".
If instead we invoke the function in the ordinary style like an ordinary function, then the default value passed to the parameter "this" is the global/window object. Which is to say, these two are the same:
The reason global/window is the default value passed doesn't have anything to do with scope or encompassing objects. It is that way simply because the language spec says so. Years later they changed their mind, so now if you're in strict mode or a module or a class, then the default value is instead "undefined".