Accessing parent 'this' inside a jQuery $.getJSON

Posted by JP on Stack Overflow See other posts from Stack Overflow or by JP
Published on 2010-03-22T23:41:49Z Indexed on 2010/03/22 23:51 UTC
Read the original article Hit count: 270

Filed under:

I'm going to assume that the overall structure of my code as it currently stands is 'best', otherwise this question gets too long, but if I've made any obvious mistakes (or if I've made life hard for myself) then please correct away!

Using jQuery, I have a javascript 'class' set out something like this:

function MyClass () {
  this.noise = "Woof"
  this.dostuff = function() {
    $.getJSON("http://cows.go",function(moo) {
      this.noise = moo.inEnglish;
    }
  }
}

var instance = new MyClass();
instance.doStuff()
console.log(instance.noise)

I'm expecting some kinda tea drinking moo in the console, but of course I'm getting an error about this.noise not being defined (because $.getJSON doesn't pass this through, right?)

Any suggestions as to how to be able to affect instance.squeak for any and all instances of MyClass without interference?

© Stack Overflow or respective owner

Related posts about jQuery