Skip to content

Instantly share code, notes, and snippets.

@jdfm
Created May 20, 2015 20:53
Show Gist options
  • Save jdfm/a1d82cbe6ec5af0e90e6 to your computer and use it in GitHub Desktop.
Save jdfm/a1d82cbe6ec5af0e90e6 to your computer and use it in GitHub Desktop.
bind an array of items to a function at once
/**
* I feel like javascript functions are missing a method. Here's why:
* call is to bind as apply is to ?
*
* Javascript lacks a native method of binding an array as a list of parameters
* to a function. Here's what I came up with:
*/
if(Function.prototype.bind && !Function.prototype.bundle){
Function.prototype.bundle = function(thisArg, argsArray){
return this.bind.apply(this, [thisArg].concat(Object.prototype.toString.call(argsArray) === '[object Array]'? argsArray: []));
};
}
if (!Function.prototype.bind && !Function.prototype.bundle) {
// Adapted from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind (changed very little)
Function.prototype.bundle = function (oThis, argsArray) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bundle - what is trying to be bound is not callable");
}
var aArgs = Object.prototype.toString.call(argsArray) === '[object Array]'? argsArray: [],
fToBundle = this,
fNOP = function () {},
fBundled = function () {
return fToBundle.apply(this instanceof fNOP? this: oThis || window /* replace with global if using nodejs */, [].concat.apply(aArgs, arguments));
};
fNOP.prototype = this.prototype;
fBundled.prototype = new fNOP();
return fBundled;
};
}
var testFunc = function(a, b, c){
console.log('a,b,c: ', a, b, c);
console.log('arguments.length: ', arguments.length);
console.log('arguments content', arguments);
};
var someArray = [1, 2, 3, 4];
var bundledFunc = testFunc.bundle(null, someArray);
var boundFunc = testFunc.bind(null, 1, 2, 3, 4);
bundledFunc();
boundFunc();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment