4 ms·
blows dust off JavaScript skills... 'this' is always 'window', unless the function is invoked as a method, i.e., as a property of an object: window.bar =
by koningrobot 18y ago
blows dust off JavaScript skills...
'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:
obj.foo.call(window) === 'bar';
foo.apply(obj, []) === 'foo';
'call' and 'apply' are the same, except that apply takes an array of function arguments, whereas call takes arguments directly.
Note that the terms 'method' and 'function' are my own here, I'm not sure what to call the two forms of invocation.
- kragen 18y agoWow, you're right. And here I thought I knew JavaScript!
- axod 18y ago>> "'this' is always 'window', unless the function is invoked as a method, i.e., as a property of an object:" More generally, 'this' is usually 'the global object'... would be more correct. And in a browser context, the global object is 'window'.