Skip to content

Instantly share code, notes, and snippets.

@njif
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save njif/a3c8845ca2167dfd0d82 to your computer and use it in GitHub Desktop.

Select an option

Save njif/a3c8845ca2167dfd0d82 to your computer and use it in GitHub Desktop.
Cross-browser bind
// Try this: https://github.com/es-shims/es5-shim
Function.prototype.bind = (function() {
if (Function.prototype.bind)
return Function.prototype.bind;
function bind(context) {
var func = this;
var bindArgs = Array.prototype.slice.call(arguments, 1);
function wrapper() {
var args = Array.prototype.slice.call(arguments);
var unshiftArgs = bindArgs.concat(args);
return func.apply(context, unshiftArgs);
}
return wrapper;
}
return bind;
}());
// Usage example:
var func = function(val) {
this._val = val;
};
func.prototype = {
add: function(val) {
var i;
for (i = 0; i < arguments.length; i++)
this._val += arguments[i];
return this;
},
val: function() {
return this._val;
}
};
var a = new func(1);
var add = a.add.bind(a);
console.assert(add(2).add(3).val() === 6, 'should be 6 (p.s.: 1 + 2 + 3)');
var b = new func(1);
var add = b.add.bind(b, 2);
add(3);
add(4, 5);
console.assert(b.val() === 17, 'should be 17 (p.s.: 1 + (2 + 3) + (2 + 4 + 5))');
var c = new func(1);
var addF = c.add.bind(c, 2);
console.assert(addF().add(3).val() === 6, 'should be 6 (p.s.: 1 + 2 + 3)');
@njif
Copy link
Author

njif commented Oct 14, 2014

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