Skip to content

Instantly share code, notes, and snippets.

@mkuklis
Last active December 15, 2015 21:58
Show Gist options
  • Save mkuklis/5329126 to your computer and use it in GitHub Desktop.
Save mkuklis/5329126 to your computer and use it in GitHub Desktop.
playing with bind, call and apply
var foo = function () {
console.log(this);
console.log(arguments);
}
var context = {};
// shortcut with predefined context and arguments
var bar = Function.prototype.call.bind(foo, context, 'arg1', 'arg2');
bar('arg3'); // context, ["arg1", "arg2", "arg3"]
// shortcut without arguments and context
var bar = Function.prototype.call.bind(foo);
bar(context, 'arg1', 'arg1', 'arg2') // context, ["arg1", "arg2", "arg3"]
// shortcut with current context
var bar = Function.prototype.call.bind(foo, undefined);
bar('arg1', 'arg2', 'arg3') // Window, ["arg1", "arg2", "arg3"]
// functional approach to bind, call and apply
var bind = Function.prototype.call.bind(Function.prototype.bind);
var call = bind(Function.prototype.call, Function.prototype.call);
var apply = bind(Function.prototype.call, Function.prototype.apply);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment