Could someone please explain why ‘this’ in the following points to the DOM Object and not to Window?
$("a").click(function() {
console.log(this);
});
This yields to:
<a id="first" href="http://jquery.com">
Consider the following which should be the same scenario:
function Foo() {
this.click = function(f) {
f();
}
}
var obj = new Foo();
obj.click(function() {
console.log(this);
});
What we get here is the Window Object (what I had expected).
It’s up to the context in which the function is executed. jQuery explicitly changes the context of the callback function, whereas your function executes the function in the global context.
to change the context:
or
For further reading:
http://dailyjs.com/2012/06/18/js101-this/
http://dailyjs.com/2012/06/25/this-binding/