Skip to content

Instantly share code, notes, and snippets.

@xtbl
Created May 7, 2013 04:24
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 xtbl/5530246 to your computer and use it in GitHub Desktop.
Save xtbl/5530246 to your computer and use it in GitHub Desktop.
JavaScript this and context: usually the "this" refers to the window object as a parent, but in event handlers it refers to the element in which the event was called. Some examples.
// <a href="http://google.com">Click me</a>
function doSomething(e) {
e.preventDefault();
console.log(this);
}
var obj = {
doIt: function(e) {
e.preventDefault();
console.log(this);
}
};
//usually the "this" refers to the window object as a parent, but in event handlers it refers to the element in which the event was called
// the context is the object clicked, console displays the anchor
$('a').on('click', doSomething);
// the anonymous function sets the context to obj, so console displays obj
$('a').on('click', function(e) {
obj.doIt(e);
});
// set context using call, so console displays the anchor
$('a').on('click', function(e) {
obj.doIt.call(this,e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment