Created
July 30, 2013 18:47
-
-
Save ducin/6115669 to your computer and use it in GitHub Desktop.
binding both "this" object and optionally arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}; | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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