Skip to content

Instantly share code, notes, and snippets.

@xphere
Last active October 14, 2015 02:17
Show Gist options
  • Select an option

  • Save xphere/4292200 to your computer and use it in GitHub Desktop.

Select an option

Save xphere/4292200 to your computer and use it in GitHub Desktop.
// Binds a method to its owner, optionally adding more arguments
function bindMethod(_this, method) {
method = _this[method];
if (arguments.length <= 2) {
return method.bind(_this);
}
var args = Array.prototype.slice.call(arguments, 2);
return args.unshift(_this), method.bind.apply(method, args);
}
function MyClass(value) {
this.myMethod = function(param) {
return value + (param || 0);
}
}
v = 10;
m = new MyClass(v);
fn = bindMethod(m, 'myMethod');
fn() === v;
plus5 = bindMethod(m, 'myMethod', 5);
plus5 === v + 5;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment