Skip to content

Instantly share code, notes, and snippets.

@Ivanca
Created December 16, 2012 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ivanca/4303394 to your computer and use it in GitHub Desktop.
Save Ivanca/4303394 to your computer and use it in GitHub Desktop.
Bind that can be override with other arguments; can be used with call and apply too (mixcall & mixapply)
// New methods for all functions: mixapply, mixcall, and mixbind
// Allows you to force arguments and context even after using .bind
// To skip any argument you can use NULL
// License: Public Domain
(function () {
var __bind = Function.prototype.bind;
var toArray = function (a) {
return Array.prototype.slice.call(a);
};
Function.prototype.bind = function () {
var args = toArray(arguments);
var f = __bind.apply(this, args);
f.mixcall = mix.apply(this, args.concat(['mixcall']));
f.mixapply = mix.apply(this, args.concat(['mixapply']));
f.mixbind = mix.apply(this, args.concat(['mixbind']));
return f;
};
var mix = function (c) {
var oldArgs = toArray(arguments);
var org = this;
var op = oldArgs.pop();
return function () {
var args = toArray(arguments);
if (op === "mixapply") {
args = args[1];
args.unshift(arguments[0]);
}
var max = Math.max(args.length, oldArgs.length);
while (max--) args[max] = args[max] == null ? oldArgs[max] : args[max];
if (op === "mixbind") {
return org.bind.apply(org, args);
}
return org.apply(args[0], args.slice(1));
};
};
Function.prototype.mixcall = function () {
return mix.apply(this, toArray(arguments).concat(["mixcall"]))();
};
Function.prototype.mixapply = function () {
return mix.apply(this, toArray(arguments).concat(["mixapply"]))();
};
Function.prototype.mixbind = function () {
return mix.apply(this, toArray(arguments).concat(["mixbind"]))();
};
})();
@Ivanca
Copy link
Author

Ivanca commented Dec 16, 2012

E.g:

var foo = function(a){ return a * this; };
var bar = foo.bind(10, 500);
console.log( bar.mixcall(null, 2) ); // Return 20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment