views:

75

answers:

3

Hi,

Is there a difference between this:

var onClick = function() {

     var image = .....

     $.post("/..../...", null, function(data) { myCallback(data, image); } );
}

and

var onClick = function() {

     this.image = .....

     $.post("/..../...", null, function(data) { myCallback(data, this.image); } );
}

I am using the 'this' way, and for some reason any parameter I pass into myCallback is null??

If I output the variable before the $.post call using alert, I get a value so its not null?

+1  A: 

At the time....

function(data) { myCallback(data, this.image); }

...will be executed (after the ajax call has completed), the execution context is changed. It will be inside a jQuery object context. So at that point, this === jQuery, which as you already saw, has no image property. Hence, the error.

By the way, google for JavaScript closures and try to understand them. It's exactly what your problem is all about.

Ionuț G. Stan
so from within functions I should just use var?
mrblah
Yes, var it's ok. Why do you need "this"?
Ionuț G. Stan
I don't, I saw someone using it but it was only for class private variables
mrblah
A: 

Declaring the variable using 'var' will work thanks to the sol-called 'closure' you are creating. The 'this' keyword refers to the currently scoped object, which, depending on the situation, might refer to the function, the window object, or any other object. This scope will most definitively be different once the callback method fires and thus is not reliable.

A: 

If you intend the onClick function to represent a class (seems unlikely) "this" is appropriate as both an indicator of that, and as means to expose instance properties (since a var declared in a class instance will effectively be private).

If you do not intend onClick to represent a class then this is wholly inappropriate as it creates a confusing signal and muddies up the context footprint (whatever the context is).

annakata