Steve Rowe
Steve Rowe

Reputation: 19413

Why is "this" captured in a closure?

If I create a variable, say _this, and assign it to this, it is captured as a closure and not a reference to the current version of this. Why?

Example code:

var AnimCore = (function () {
    function AnimCore(ctx) {
        this.ctx = ctx;
    }
    AnimCore.prototype.beginAnimation = function () {
        this.animLoop();
    };
    AnimCore.prototype.animLoop = function () {
        var _this = this;
        this.ctx.drawSomething(); // removed actual drawing code, this is a proxy for it.
        window.setTimeout(function () {
            _this.animLoop();
        }, 1000 / 60);
    };
    return AnimCore;
})();

In this case, _this is bound to the initial this and not to the new this each time the function is called. Why?

[update] I now understand that the closure is happening in the anonymous function which is why _this always refers to the same thing. Next question, however, is why does this.ctx work each time? If I don't use the anonymous function, it fails after the first time.

Upvotes: 0

Views: 177

Answers (1)

LetterEh
LetterEh

Reputation: 26696

this is a special variable. It's special because its context is determined at the time you call the function with this inside.

If, however, you're assigning this to a variable, inside a closure:

var myFunc = (function () {
    var staticThis = this;
    return function () {
        staticThis.doStuff();
    };
}).call(myObj);

See what I've done?
I've got a variable called staticThis, which I am explicitly setting to be equal to myObj.
staticThis keeps the value of this (which happens to be a pointer to a specific object), rather than keeping the "magic" dynamic context resolution of this, which is saved for the this keyword.

Upvotes: 1

Related Questions