Created
May 7, 2013 04:24
-
-
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.
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
// <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