5

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

fliX
  • 773
  • 8
  • 24
  • jQuery manipulates `this` where needed. – Blaster Jul 02 '12 at 07:53
  • As usual, the MDN has some good information about this: https://developer.mozilla.org/en/DOM/element.addEventListener#The_value_of_this_within_the_handler – Niko Jul 02 '12 at 07:56
  • I think the person you should ask is John Resig who is responsible for the concept as far as I can tell - I believe it's his doing. Believe it or not - but he is [an active member here](http://stackoverflow.com/users/6524/john-resig) as well. :) – Shadow The GPT Wizard Jul 02 '12 at 07:58

4 Answers4

7

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.

penartur
  • 9,792
  • 5
  • 39
  • 50
5

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/

Gottox
  • 682
  • 6
  • 15
4

this will be decided by the context.

If you change your code to below, then this will point to some_other_object.

function Foo() {
    this.click = function(f) {
        f.call(some_other_object);
    }
}
xdazz
  • 158,678
  • 38
  • 247
  • 274
2

jQuery uses the javascript apply function when calling event handlers. From the mdn documentation:

Calls a function with a given this value and arguments provided as an array.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
aaberg
  • 2,253
  • 15
  • 14