Created
December 16, 2012 04:47
-
-
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)
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
// 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"]))(); | |
}; | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
E.g: