Adrian Baran
Adrian Baran

Reputation: 895

This of inner function when invoked by call

I have the following code:

var outer = function(){
    var that = this;
    function inner(){
        assert(this===that, "Inner === Outer");
        console.log(this);
        console.log(that);
    }
    inner();
    return this;
};

outer();
var obj = {};
outer.call(obj);

When the first invocation is executed - outer(). Everything is clear for me - the outer is called in window context and both this and that === window. Then things get wired when I invoke function outer be call function. That === obj, which is obvious, but why this === window ?

Upvotes: 2

Views: 54

Answers (1)

elclanrs
elclanrs

Reputation: 94131

Because you're losing the context by introducing a closure. this depends only on how you call the function. It can be implicit, as in the case of an object method. In your code inner is not being called with any context so it'll default to window. You can do this:

var outer = function(){
    var that = this;
    function inner(){
        assert(this===that, "Inner === Outer");
        console.log(this);
        console.log(that);
    }
    inner.call(this); // explicit context
    return this;
};

Upvotes: 5

Related Questions