Skip to content

Instantly share code, notes, and snippets.

@furf
Created April 15, 2009 22:21
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save furf/96068 to your computer and use it in GitHub Desktop.
var bind = function(fn, obj /*, defaults */) {
var scope = obj || window, defaults;
fn = (typeof fn === 'string') ? scope[fn] : fn;
// If no defaults are supplied, return the lightweight callback
if (arguments.length < 3) {
return function() {
fn.apply(scope, arguments);
};
// Otherwise, wrap with code to merge defaults with supplied arguments
} else {
defaults = Array.prototype.slice.call(arguments, 2);
return function() {
// Merge defaults with supplied arguments
var args = [];
for (var i = 0, n = Math.max(arguments.length, defaults.length); i < n; ++i) {
args[i] = (typeof arguments[i] !== 'undefined') ? arguments[i] : defaults[i];
}
fn.apply(scope, args);
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment