让我们假设我们有如下对象:
function foo( some_var ) {
this.some_var = some_var;
}
现在我们通过原型添加一些方法:
foo.prototype.method = function( value ) {
this.some_var += value;
}
然后,我们有一些方法可以解决一些问题:
foo.prototype.problematic = function( args ) {
//using jQuery $.getJSON function
$.getJSON( 'http://url.com', args, function( data ) {
for( var i in data ) {
this.method( data[i].value );
// we have error in console: "this.method is not a function"
// this doesn't point to object foo, but to data which are returned by $.getJSON function
}
}
}
正如我在上面的评论中提到的,我们在Firebug控制台中有一个错误:“this.method不是函数”。这是因为我们的“this”并没有指向foo。我不想做这样的事情:
var self = this;
然后使用变量self而不是这个,因为我在对象变量中进行了很多更改。
提前感谢您的帮助。 干杯
答案 0 :(得分:0)
您可以使用.ajax()
代替.getJSON()
,因为这样可以指定上下文:
var self = this; // I know you don't want to use self, so let's use this as
// the context for the async callback
$.ajax({
context: this,
dataType: "json",
success: function(){
for( var i in data ) {
this.method( data[i].value ); // this == self
}
}});