Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does jQuery hijack "this"?

I'm just curious to know how jQuery is able to hijack the 'this' keyword in Javascript. From the book I'm reading: "Javascript the Definitive Guide" it states that "this" is a keyword and you cannot alter it like you can with an identifier.

Now, say you are in your own object constructor and you make a call to some jQuery code, how is it able to hijack this from you?

function MyObject(){
    // At this point "this" is referring to this object
    $("div").each(function(){
        // Now this refers to the currently matched div
    });
}

My only guess would be that since you are providing a callback to the jQuery each() function, you are now working with a closure that has the jQuery scope chain, and not your own object's scope chain. Is this on the right track?

thanks

like image 309
D.C. Avatar asked Feb 05 '10 00:02

D.C.


1 Answers

You can change the context of a function (i.e. the this value) by calling it with .call() or .apply() and passing your intended context as the first argument.

E.g.

function fn() {
    return this.foo;
}

fn.call({foo:123}); // => 123

Note: passing null to either call or apply makes the context the global object, or, in most cases, window.

It's probably worth noting the difference between .apply() and .call(). The former allows you to pass a bunch of arguments to the function it's being applied to as an array, while the latter lets you just add them as regular arguments after the context argument:

someFunction.apply( thisObject, [1,2,3] );
someFunction.call( thisObject, 1, 2, 3 );

From the jQuery source:

for ( var value = object[0];
      i < length &&
      callback.call( value, i, value ) // <=== LOOK!
      !== false;
      value = object[++i] ) {}
like image 180
James Avatar answered Nov 14 '22 22:11

James