Skip to content

Instantly share code, notes, and snippets.

@ducin
Created July 30, 2013 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ducin/6115669 to your computer and use it in GitHub Desktop.
Save ducin/6115669 to your computer and use it in GitHub Desktop.
binding both "this" object and optionally arguments
// binding both "this" object and optionally arguments
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(thisObject) {
var fun = this, boundArgs = Array.prototype.slice.call(arguments, 1);
return function() {
var allArgs = boundArgs;
if (arguments.length) {
allArgs = allArgs.concat(Array.prototype.slice.call(arguments));
}
fun.apply(thisObject, allArgs);
};
};
}
// run it with `node test.js`
require('./bind.js')
function buy(what) {
console.log(this.name + " is goint to buy " + what);
}
var blake = {
name: 'William Blake',
occupation: 'painter'
};
var blakeBuys = buy.bind(blake);
var blakeBuysOranges = buy.bind(blake, 'oranges');
var caesar = {
name: 'Julius Caesar',
occupation: 'emperor'
};
var caesarBuysSoldiers = buy.bind(caesar, 'soldiers');
buy();
blakeBuys();
blakeBuys('a car');
blakeBuysOranges();
caesarBuysSoldiers();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment