开发者

Accessing parent 'this' inside a jQuery $.getJSON

开发者 https://www.devze.com 2022-12-24 07:14 出处:网络
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

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 开发者_Python百科affect instance.squeak for any and all instances of MyClass without interference?


You gotta love the guy who invented closures:

function MyClass () {
  this.noise = "Woof"

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

精彩评论

暂无评论...
验证码 换一张
取 消