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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.