Last active
October 14, 2015 02:17
-
-
Save xphere/4292200 to your computer and use it in GitHub Desktop.
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
| // Binds a method to its owner, optionally adding more arguments | |
| function bindMethod(_this, method) { | |
| method = _this[method]; | |
| if (arguments.length <= 2) { | |
| return method.bind(_this); | |
| } | |
| var args = Array.prototype.slice.call(arguments, 2); | |
| return args.unshift(_this), method.bind.apply(method, args); | |
| } |
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 MyClass(value) { | |
| this.myMethod = function(param) { | |
| return value + (param || 0); | |
| } | |
| } | |
| v = 10; | |
| m = new MyClass(v); | |
| fn = bindMethod(m, 'myMethod'); | |
| fn() === v; | |
| plus5 = bindMethod(m, 'myMethod', 5); | |
| plus5 === v + 5; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment