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).
In Javascript, OOP is different from what you're accustomed to in languages like Java.
Basically, it is easier to think that there is no OOP and that this
is just a "hidden argument" of functions.
For example, when you see
function f(x, y, z) {
console.log(this, x, y, z);
}
think that in common OOP languages (such as Java) that would be
function f(this, x, y, z) {
console.log(this, x, y, z);
}
When you see var a = b.f(x, y, z);
, think var a = f(b, x, y, z)
.
When you see var a = f(x, y, z);
think var a = f(undefined, x, y, z);
(In browser environment, when strict mode is not activated, it is f(window, x, y, z);
)
Now it should be easier to understand why this
in your example means different things in the nested scopes.
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:
function Foo() {
this.click = function(f) {
f.apply(this);
}
}
or
function Foo() {
this.click = function(f) {
this.f = f
this.f();
}
}
For further reading:
http://dailyjs.com/2012/06/18/js101-this/
http://dailyjs.com/2012/06/25/this-binding/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With