Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this closure have access to the 'this' keyword? - jQuery

I'm a beginner to closures (and Javscript in general), and I can't find a satisfactory explanation as to what's going on in this code:

function myObject(){
    this.myHello = "hello";
    this.myMethod = do_stuff;
}

function do_stuff(){
    var myThis = this;
    $.get('http://example.com', function(){
        alert(this.myHello);
        alert(myThis.myHello);
    });
}

var obj = new myObject;
obj.myMethod();

It will alert 'undefined' and then 'hello'. Obviously this should not be jQuery specific, but this is the simplest form of my original code I could come up with. The closure in do_stuff() has access to the variables in that scope, but apparently this rule does not apply to the this keyword.

Questions:

What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())? Does myThis contain a copy of this or a reference to it? Is it generally not a good idea to use this in closures?

Any response much appreciated.

like image 759
thewiglaf Avatar asked Jul 23 '10 23:07

thewiglaf


People also ask

What is scope of this keyword?

If a function which includes 'this' keyword, is called from the global scope then this will point to the window object. Learn about global and local scope here. In the above example, a function WhoIsThis() is being called from the global scope. The global scope means in the context of window object.

How does the this keyword work?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.

What is this keyword in JavaScript stack overflow?

this is a keyword in JavaScript that is a property of an execution context. Its main use is in functions and constructors.

What would happen if I remove the closure feature from JavaScript?

If JavaScript did not have closures, then more states would have to be passed between functions explicitly, making parameter lists longer and code noisier. So, if you want a function to always have access to a private piece of state, you can use a closure.


2 Answers

What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())?

Each function has its own execution context, the this keyword retrieves the value of the current context.

The doStuff identifier and the obj.myMethod property refer to the same function object, but since you are invoking it as a property of an object (obj.myMethod();), the this value inside that function, will refer to obj.

When the Ajax request has succeeded, jQuery will invoke the second function (starting a new execution context), and it will use an object that contains the settings used for the request as the this value of that callback.

Does myThis contain a copy of this or a reference to it?

The myThis identifier will contain a reference to the object that is also referenced by the this value on the outer scope.

Is it generally not a good idea to use this in closures?

If you understand how the this value is handled implicitly, I don't see any problem...

Since you are using jQuery, you might want to check the jQuery.proxy method, is an utility method that can be used to preserve the context of a function, for example:

function myObject(){
    this.myHello = "hello";
    this.myMethod = do_stuff;
}

function do_stuff(){
    $.get('http://example.com', jQuery.proxy(function(){
        alert(this.myHello);
    }, this)); // we are binding the outer this value as the this value inside
}

var obj = new myObject;
obj.myMethod();

See also:

  • ‘this’ object can’t be accessed in private JavaScript functions without a hack?
like image 177
Christian C. Salvadó Avatar answered Sep 21 '22 12:09

Christian C. Salvadó


$.get('http://example.com', function(){
    alert(this.myHello);  // this is scoped to the function
    alert(myThis.myHello);  // myThis is 'closed-in'; defined outside
});

note the anonymous function. this in that scope is the scope of the function. myThis is the this of the outer scope, where the myHello has been defined. Check it out in firebug.

'this' always refers to the current scope of execution, i believe. If you want to take the current scope and preserve it, you do what you did, which is assign this to another variable.

like image 45
hvgotcodes Avatar answered Sep 21 '22 12:09

hvgotcodes