Does anybody know? Couldn't find this question asked before, even though it seems fairly basic.
views:
82answers:
2
+3
A:
The context
(the this
keyword) it's not completely implicit, it can be set and changed explicitly.
For example:
function test () {
alert(this);
}
test.call("Hello world");
The test
function is called with a string as the context.
So in conclusion, you cannot know what this
is unless you explicitly define it, or you are inside the function.
CMS
2009-11-14 19:27:11
Aha, bummer. (here)
kaleidomedallion
2009-11-14 19:38:03
+2
A:
The same function will see different values of this
depending on how it called. See Crockford for details, but there are four cases:
- Invoked as a simple function, it is bound to the global/window object.
- Invoked as a method on an object, it refers to that object.
- Invoked as a constructor via the
new
keyword, it is the newly instantiated object, which inherits from the object stored in function's ownprototype
property. - Invoked by its own
apply
orcall
method, it is the first argument supplied.
If these cases sound complex, tedious, and error-prone, all the more reason to avoid relying on this
outside of methods, where it makes the most sense anyway.
ewg
2009-11-14 21:01:41