Last active
December 20, 2015 10:30
-
-
Save ducin/6115374 to your computer and use it in GitHub Desktop.
binding "this" object to a function
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 "this" object only (function arguments are ignored) | |
if (!Function.prototype.bind) { | |
Function.prototype.bind = function bind(thisObject) { | |
var fun = this; | |
return function() { | |
fun.apply(thisObject, 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
// run it with `node test.js` | |
require('./bind.js') | |
function introduce() { | |
console.log("My name is " + this.name); | |
} | |
var blake = { | |
name: 'William Blake', | |
occupation: 'painter' | |
}; | |
var introduceBlake = introduce.bind(blake); | |
var caesar = { | |
name: 'Julius Caesar', | |
occupation: 'emperor' | |
}; | |
var introduceCaesar = introduce.bind(caesar); | |
introduce(); | |
introduceBlake(); | |
introduceCaesar(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment