Last active
August 29, 2015 14:10
-
-
Save jdfm/3d5ea10ebabbb58cbfce to your computer and use it in GitHub Desktop.
Extract bind, call and apply to use as standalone functions, instead of as methods of other functions.
This file contains 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
var bind = Function.prototype.bind ? Function.prototype.bind.bind(Function.prototype.call) : (function(){ | |
/** | |
* Some browsers don't have the bind function, so you can use the code | |
* below to achieve more or less the same results... A more complete | |
* implementation of binder can be found on mdn, this was just a quick hack. | |
*/ | |
function binder(fn, that){ | |
for(var i = 0, iLen = arguments.length, arr = new Array(iLen); i < iLen; i++){ | |
arr[i] = arguments[i]; | |
} | |
arr.splice(0, 2); | |
return function(){ | |
for(var j = 0, jLen = arguments.length, arr2 = new Array(jLen); j < jLen; j++){ | |
arr2[j] = arguments[j]; | |
} | |
[].unshift.apply(arr2, arr); | |
return fn.apply(that, arr2); | |
}; | |
} | |
return binder(Function.prototype.call, binder, Function.prototype.call); | |
}()); | |
var call = bind(Function.prototype.call); | |
var apply = bind(Function.prototype.apply); | |
var test = function(a){ console.log('hey', this, a); }; | |
bind(test, {a:1}, 1)() | |
call(test, {a:1}, 1) | |
apply(test, {a:1}, [1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment