This is a little weirder than it seems, because of a variable called `this'. You see, `this' is set inside of a function whenever you call it, based on how you've called it. It can be set a couple of ways:
foo(arg1, arg2, ...); // sets `this' to the global object (in a browser, that's `window')
foo.call(o, arg1, arg2, ...); // sets `this' to `o'
foo.apply(o, [arg1, arg2, ...]); // sets `this' to `o' (same as `call')
None of these are the way you usually set `this' on function invocation, however. Usually, `this' is set automatically when you invoke a function which happens to be a property of an object. So, for example:
bar = { foo: function (x,y) { var thatThing = this; ... } };
bar.foo(1,2) - sets `this' (and `thatThing') to 'bar'.
However (!!!), if you say:
foo2 = bar.foo;
foo2();
The `this' inside of your function, as well as `thatThing', will both be set to `window'.
'this' is always 'window', unless the function is invoked as a method, i.e., as a property of an object:
window.bar = 'bar'
var obj = {
foo: function () { return this.bar },
bar: 'foo'
};
obj.foo() === 'foo'; // invoked as a method
foo = obj.foo;
foo() === 'bar'; // invoked as a function
// this reveals some oddness imho:
(obj.foo)() === 'foo'; // invoked as a method
(foo = obj.foo)() === 'bar'; // invoked as a function
Note that 'this' defaults to 'window' not because 'foo()' is equivalent to 'window.foo()'; 'foo' could be a local variable referring to a function and 'this' would refer to 'window' all the same. There's no rationale for this that I know of, it's just the way it works (in ES3 at least: ES4 does what you expected).
When you use the Function::call and Function::apply methods, you get to specify what 'this' should refer to:
This is a little weirder than it seems, because of a variable called `this'. You see, `this' is set inside of a function whenever you call it, based on how you've called it. It can be set a couple of ways:
None of these are the way you usually set `this' on function invocation, however. Usually, `this' is set automatically when you invoke a function which happens to be a property of an object. So, for example: However (!!!), if you say: The `this' inside of your function, as well as `thatThing', will both be set to `window'.details here: https://developer.mozilla.org/en/Core_JavaScript_1.5_Referen...