1
//this is a class
function SpriteSheetClass()
{
    this.sprite="local";

    $.getJSON(url, this.onLoaded);      
}   

SpriteSheetClass.prototype.onLoaded= function(json) 
{
    console.log(this.sprite); //returns undefined!

    //I am out of SpriteSheetClass scope! how do I store the json???
}

var a=new SpriteSheetClass()

When the getJSON callback is executed, the scope is not in the class. There is no way to bind the returned json with my class instance (a)

Keep in mind I want to keep the calls async, and I need to create many instances of SpriteSheetClass This is not a timing question, it is a scope question.

thanks

3 Answers 3

1

When the callback function is called, this will not be the object, but the $.getJSON function.

You can bind the value of this to the callback, so it will be the object instead

$.getJSON(url, this.onLoaded.bind(this));

FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

1

With modern day browsers you can use function.bind(thisArg) to keep the proper scope.

function SpriteSheetClass() {
    this.sprite="local";
    $.getJSON(url, this.onLoaded.bind(this));
}   

Comments

0

A local wrapper function will do the job:

function SpriteSheetClass() 
{
   this.sprite="local";
   var that = this;

   var callback = function(data) {
     that.onLoaded(data);
   };

   $.getJSON(url, callback);
}   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.