this value in JavaScript anonymous function

27,941

Solution 1

this is special. It refers to the object that the function is being called on behalf of (most commonly via dot syntax).

So, in the case of A, the function is being called on behalf of a new MyObject object. B is in a different function that isn't explicitly being called on behalf of any object, so this defaults to the global object (window).

In other words, this changes depending on how the function is called, not where or how it is defined. The fact that you're using an anonymous function (defined inside another function) is coincidental and has no effect on the value of this.

Solution 2

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)

Solution 3

In the anonymous function, this is bound to the global object (window in a browser environment).

There are various ways of accessing the instance:

var self = this;
(function () {
    console.log("B", self instanceof MyObject);
}());

or

(function () {
    console.log("B", this instanceof MyObject);
}).call(this);

Solution 4

this is set based on how you call the function.
Your anonymous function is a normal function call, so this is the global object.

You could write (function() { ... }).call(this) to explicitly call it with your this.

Share:
27,941
Corno
Author by

Corno

Software Developer living in Delft, the Netherlands. I've used many languages, but never has one been such a good match for me like TypeScript is. I love data and datastructuring more than algorithms.

Updated on February 14, 2020

Comments

  • Corno
    Corno over 4 years

    Can anybody explain to me why A is true and B is false? I would have expected B to be true as well.

    function MyObject() {
    
    };
    
    MyObject.prototype.test = function () {
        console.log("A", this instanceof MyObject);
        (function () {
            console.log("B", this instanceof MyObject);
        }());
    }
    
    new MyObject().test();
    

    update: since ecmascript-6 you can use arrow functions which would make it easy to refer to MyObject like this:

    function MyObject() {
    
    };
    
    MyObject.prototype.test = function () {
        console.log("A", this instanceof MyObject);
        (() => {//a change is here, which will have the effect of the next line resulting in true
            console.log("B", this instanceof MyObject);
        })(); //and here is a change
    }
    
    new MyObject().test();