6 ms·
Simple(r) explanation; this is whatever is "left" of the function call (i.e - obj.method() => this === obj inside the called method), unless you've used .bind/c
by eiriklv 9y ago
Simple(r) explanation; this is whatever is "left" of the function call (i.e - obj.method() => this === obj inside the called method), unless you've used .bind/call/apply which explicitly sets what this should be via an argument.
If you're doing a direct function call like myFunc() there is nothing "left" of the function call. But you might think of it as actually doing window.myFunc(), which again explains why this === window. In strict mode this behavior has been "fixed" so that this === undefined.
It's all about how a function is called.
- Cakez0r 9y agoWhat about setTimeout(obj.method, 1)? (Spoilers: this == window, not what is left of the function call)
- nhpatt 9y agoYou are not calling the function, you are passing a reference to setTimeout that calls it directly, without the obj. before the call. @getify explains it flawlessly, there are 4 modes: new, obj., bind/apply/call and default (window or error in strict mode)
- eiriklv 9y agoAs nhpatt notes you're not actually calling obj.method here, you're passing it as an argument, which will be called at a later time. Looking at a possible implementation of setTimeout makes it clearer: function setTimeout(func, delay) { // wait for the delay to complete.. func(); } Here you can see that when the function is called there's nothing to the left of it.
- Cakez0r 9y agoYup, I get it. I was just pointing out that there are some edge cases to the "context is whatever is left of the function" rule-of-thumb.