"this" is different in every function. Inside your processJSONFunc()
callback, "this" is not what you might expect - as you discovered. That
function is not being called as a method of your object.

As you also discovered, you do have complete access to *local variables*
defined in the parent function, and that is the best solution. You can
either reference these variables directly as in your example, or if you want
access to all the properties of your object's "this", simply save a
reference to it in a local variable.

At the beginning of the MyWidgetObject contstructor, you can add:

    var obj = this;

And then you can use "obj" everywhere that you would otherwise use "this".
For example, alert(obj.parentObject) would work exactly as you want.

"obj" is not a magic name; you can use any variable name for this purpose.
You'll often see "self" used for this purpose, but I don't recommend that
particular name because it's a bit error-prone. If you forget to assign a
value into self, then self will be a reference to the window object which is
not what you want.

-Mike

> From: Yazan
> 
> Hi all,
> 
> I trying to understand the right way to access the properties 
> of my object from within a function called by the $.getJSON 
> function. Here is an example of what I have:
> 
> function MyWidgetObject(_parentObject){
>     this.parentObject = _parentObject;
> 
>     this.jsonFunc = function(){
>         $.getJSON("json.js", this.processJSONFunc);
> 
>     }
> 
>     this.processJSONFunc = function(jsonObj){
> 
>     //this doesn't work, tells me its undefined
>     alert(this.parentObject);
> 
>     //this DOES work
>     alert(_parentObject);
> 
>     }
> 
> 
> }
> 
> My question is: what is the best way to access the properties 
> of the MyWidgetObject, like MyWidgetObject.parentObject ? 
> Please let me know if I can provide any more information. 
> Thanks for reading!
> 

Reply via email to