2010-09-24 70 views
0

讓我們假設我們有對象像下面這樣:啓動jQuery對象方法中

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.meth od不是一個功能「。這是因爲我們的「這個」並不指向對象foo。我不想做這樣的事情:

var self = this; 

,然後用自變量,而不是這個,因爲我做了很多O對象變量中的變化。

在此先感謝您的幫助。 乾杯

回答

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 
     } 
}}); 
+0

感謝,招與背景:這完美的作品 – 2010-09-24 14:20:19