Skip to content

Instantly share code, notes, and snippets.

@daniel-aranda
Last active February 25, 2016 06:05
Show Gist options
  • Save daniel-aranda/5722fdb89a873ee5d066 to your computer and use it in GitHub Desktop.
Save daniel-aranda/5722fdb89a873ee5d066 to your computer and use it in GitHub Desktop.
Node.js :: This is how you should use anonymous functions if you do not want to lose the scope of this

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment