Skip to content

Instantly share code, notes, and snippets.

@lackneets
Last active December 22, 2015 11:44
Show Gist options
  • Save lackneets/5aae174a9049b0aceda3 to your computer and use it in GitHub Desktop.
Save lackneets/5aae174a9049b0aceda3 to your computer and use it in GitHub Desktop.
Bind all instance methods
function MyController(){
// Bind all
for (var method in this.constructor.prototype) {
this[method] = this[method].bind(this);
}
/* Equals to
this.render = this.render.bind(this);
this.filter = this.filter.bind(this);
...
*/
}
MyController.prototype.render = function(){
console.log('ThisArg in render is', this);
return this.filter(/*something*/); // Without binding, this will crash
}
MyController.prototype.filter = function(){
console.log('ThisArg in filter is', this);
}
var contoller = new MyController();
setTimeout(contoller.render, 1); // This type of callback will lose this
/* Results are:
ThisArg in render is MyController {}
ThisArg in filter is MyController {}
*/
function MyController(){
// without bind, try this yourself
}
MyController.prototype.render = function(){
console.log('ThisArg in render is', this);
return this.filter(/*something*/); // Without binding, this will crash
}
MyController.prototype.filter = function(){
console.log('ThisArg in filter is', this);
}
var contoller = new MyController();
setTimeout(contoller.render, 1); // This type of callback will lose this
/* Results are:
ThisArg in render is Window {…}
Uncaught TypeError: this.filter is not a function
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment