views:

82

answers:

2

Does anybody know? Couldn't find this question asked before, even though it seems fairly basic.

+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
Aha, bummer. (here)
kaleidomedallion
+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:

  1. Invoked as a simple function, it is bound to the global/window object.
  2. Invoked as a method on an object, it refers to that object.
  3. Invoked as a constructor via the new keyword, it is the newly instantiated object, which inherits from the object stored in function's own prototype property.
  4. Invoked by its own apply or call 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