Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: this variable and callbacks

Tags:

javascript

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?

like image 426
Eugeny89 Avatar asked Oct 24 '25 16:10

Eugeny89


1 Answers

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.

like image 111
pimvdb Avatar answered Oct 26 '25 08:10

pimvdb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!