javascriptthis

Why is `this` the global object inside an internal function called from within a method?


Ok, so I thought I understood this (no pun intended), but apparently not.

var Constructor = function () {
    var internalFunction = function () {
        return this === window;
    };
    this.myMethod = function () {
        alert(internalFunction());
    };
};
var myObj = new Constructor();
myObj.myMethod();

This alerts true. Why can't the internal function see this as the object? Instead I have to use alert(internalFunction.call(this)); in myMethod.

Edit: I was looking for an explanation as to why this is assigned in that way, not workarounds such as var self = this;, etc. Sorry if I didn't make that clear.


Solution

  • this is not bound until the function is called and is dependent on how the function is called. You could think of it as an extra parameter implicitly passed to the function.

    In this case, the problem is that you're calling internalFunction using internalFunction(). The this value is set either by calling a function as a method (as in foo.bar() or foo["bar"]()) or by setting this explictly via call() or apply(). Your call is doing neither so this reverts to the global object.

    The simplest way to achieve what you want in this case while keeping internalFunction private is to store a reference to this inside the constructor function:

    var Constructor = function() {
        var thisObj = this;
    
        var internalFunction = function () {
            return thisObj === window;
        };
    
        thisObj.myMethod = function () {
            alert(internalFunction());
        };
    }