Javascript value for 'this'

Can someone explain why 'this' in the following paragraphs is a DOM Object and not in a Window?

$("a").click(function() {
    console.log(this);
});

This gives:

<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 is a Window object (what I expected).

+5
source share
4 answers

To the context in which the function is executed. jQuery explicitly changes the context of the callback function, while your function executes the function in a 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/

+5
source

In Javascript, OOP is different from what you are used to in languages ​​like Java.

, , this " " .

,

function f(x, y, z) {
    console.log(this, x, y, z);
}

, ( Java),

function f(this, x, y, z) {
    console.log(this, x, y, z);
}

var a = b.f(x, y, z);, var a = f(b, x, y, z).

var a = f(x, y, z); think var a = f(undefined, x, y, z); ( , , f(window, x, y, z);).

, this .

+6

this .

, this some_other_object.

function Foo() {
    this.click = function(f) {
        f.call(some_other_object);
    }
}
+4

jQuery javascript apply . mdn:

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

+2
source

All Articles