this value in JavaScript anonymous function

Inside of your anonymous function this is the global object.

Inside of test, this is the instance of MyObject on which the method was invoked.


Whenever you call a function like this:

somceFunction(); // called function invocation

this is always the global object, or undefined in strict mode (unless someFunction was created with bind** — see below)

Whenever you call a function like this

foo.someMethod();  //called method invocation

this is set to foo


**EcmaScript5 defines a bind function that allows you to create a function that has a pre-set value for this

So this

    var obj = { a: 12 };
    var someFunction = (function () { alert(this.a); }).bind(obj);
    someFunction();

Causes someFucntion to be invoked with this equal to obj, and alerts 12. I bring this up only to note that this is a potential exception to the rule I mentioned about functions invoked as

someFunction();

always having this equal to the global object (or undefined in strict mode)

Leave a Comment