Accessing parent 'this' inside a jQuery $.getJSON
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;
}
}
}
精彩评论