Skip to content

Instantly share code, notes, and snippets.

@boscomonkey
Created January 21, 2012 21:26
Show Gist options
  • Save boscomonkey/1654080 to your computer and use it in GitHub Desktop.
Save boscomonkey/1654080 to your computer and use it in GitHub Desktop.
In JavaScript, binds an object to a callback function to use as "this".
// In JavaScript, binds an object to a callback function to use as "this".
//
// When a function is passed as an event callback, "this" is bound to
// the DOM element triggering the event; in other scenarios when a
// function is used as a callback, "this" is bound to the window
// object.
//
// To override the default binding of "this", call bindThis on your
// function. For example:
//
// camera.shootPhoto(
// function (image) {
// // ...
// }.bindThis(someObject)
// );
//
Function.prototype.bindThis = function (context) {
var self = this;
return function () { self.apply(context, arguments); }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment