Skip to content

Instantly share code, notes, and snippets.

@ducin
Last active December 20, 2015 10:30
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/6115374 to your computer and use it in GitHub Desktop.
Save ducin/6115374 to your computer and use it in GitHub Desktop.
binding "this" object to a function
// 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);
};
};
}
// 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