4

Consider the following code

Class.prototype.init = function() {
    var self = this;
    var onComplete = function() {
        self.a.doSomethingElse(self._go);
    };

    console.log(this); //prints Object {...}
    this.a.doSomething(onComplete); //onComplete is called inside a
};

Controller.prototype._go = function(map) {
    console.log(this); //prints 'Window'
};

The question is why this is equal to window inside _go function?

1 Answer 1

5

The binding of the object by calling a property only applies when directly calling it. When just accessing the property and calling it later on (by e.g. passing it to a callback), the object binding is not kept.

The behaviour comes down to the following:

var a = {
  b: function() {
    console.log(this);
  }
};

a.b(); // logs a, because called directly

var func = a.b;
func(); // logs window, because not called directly

In your case, you could just as well pass Controller.prototype._go since it refers to the very same function. The solution is to use self._go.bind(self) to keep the binding.

Not the answer you're looking for? Browse other questions tagged or ask your own question.