Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of 'this' in Javascript

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).

like image 436
fliX Avatar asked Jul 02 '12 07:07

fliX


2 Answers

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.

like image 137
penartur Avatar answered Oct 06 '22 13:10

penartur


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/

like image 39
Gottox Avatar answered Oct 06 '22 12:10

Gottox