Created
August 25, 2014 14:46
-
-
Save cristobal/9e857ec7d28c7479992b to your computer and use it in GitHub Desktop.
JavaScript bind
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
| // If you don't need new for bound functions do this | |
| function bind(fn, c) { | |
| if (Function.prototype.bind && | |
| fn.bind === Function.prototype.bind) { | |
| return Function.prototype.bind.apply(fn, | |
| Array.prototype.slice.call(arguments, 1)); | |
| } | |
| var args = Array.prototype.slice.call(arguments, 2); | |
| return function () { | |
| return fn.apply(c, args.concat( | |
| Array.prototype.slice.call(arguments))); | |
| } | |
| } | |
| // Else for new bound function support | |
| function bind(fn, c) { | |
| var args = Array.prototype.slice.call(arguments, 2), | |
| ctor = function () {}, | |
| bound = function () { | |
| return fn.apply( | |
| this instanceof ctor ? this : c, | |
| args.concat( | |
| Array.prototype.slice.call(arguments)) | |
| ); | |
| }; | |
| ctor.prototype = fn.prototype; | |
| bound.prototype = new ctor; | |
| return bound; | |
| } | |
| // or look at the following codes: | |
| // * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind | |
| // * https://github.com/jashkenas/underscore/blob/master/underscore.js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment