What does ‘this’ evaluate to?
I tried to pin this down (without reference to the actual language spec, so apologies if I get any details incorrect)
- What is the function object whose definition contains the code currently executing?
- What kind of syntax was used at the point this particular function object was called?
- Called explicitly as a property of an object, as in: someObject.propertyName(someArg), where someObject.propertyName == yourFunction
- Then 'this' is 'someObject' from the above. this is the most common way for the value of 'this' to be decided.
- As yourFunction.call(abc, someArg), or yourFunction.apply(abc, [someArg])
- Then 'this' is 'abc' from the above
- Neither of the above - when called as eg someLocalVariable() or someGlobalVariable()
- Within a 'with' block, as in with(foo) { yourFunction() }
- Then 'this' is 'foo' from the above
- At the top-level within javascript defined in a script tag in a browser
- Then 'this' is the 'window' object
- From the top-level in event handler code defined in an HTML attribute in a browser
- Then 'this' is the DOM element concerned
- From the top-level in some other javascript execution environment
- Implementation-defined
- When called by some code outside your control
- Could be anything
- If you want to fix the value of 'this', then before handing your function over as a callback, wrap it up inside an closure which explicitly calls apply with your intended value of this:
- var myFunction = some.expression; var callMeBack = function() { myFunction.apply(intendedFixedValueOfThis, arguments) }
- Or use eg Function.prototype.bind from prototype, dojo.hitch from dojo