Traditional callbacks:
asyncObject.method(function(){
//TODO: stuff
});
Binding the scope to currentObject
asyncObject.method(function(){
//TODO: stuff
}.bind(scope));
//run: node example.js | |
var asyncEngine = { | |
load: function(callback){ | |
callback.call(); | |
} | |
}; | |
var MyClass = function( | |
){ | |
this.sheIsTheOne = true; | |
}; | |
MyClass.prototype.sheIsTheOne = null; | |
MyClass.prototype.properBind = function(){ | |
asyncEngine.load(function(){ | |
console.log('this is a proper bind. Checking property of class, she is the one:', this.sheIsTheOne ); | |
}.bind(this)); | |
}; | |
MyClass.prototype.traditionalCallback = function(){ | |
asyncEngine.load(function(){ | |
console.log('traditional callback. Checking property of class, she is the one:', this.sheIsTheOne ); | |
}); | |
}; | |
var test = new MyClass(); | |
test.properBind(); | |
test.traditionalCallback(); |
//You should pass the anonymous function binding the current object to it. | |
//Traditional callbacks: | |
asyncObject.method(function(){ | |
//TODO: stuff | |
}); | |
//Binding the scope to currentObject | |
asyncObject.method(function(){ | |
//TODO: stuff | |
}.bind(scope)); | |
//Bonus: this also avoid to use the ugly "trick" of use var self = this; to use self in callbacks :P |