Last active
December 22, 2015 11:44
-
-
Save lackneets/5aae174a9049b0aceda3 to your computer and use it in GitHub Desktop.
Bind all instance methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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