2010-11-01 36 views
1

我有一個像這樣的JS對象。

function Product() { 
    this.prop1 = 1; 
    this.prop2 = 2; 
} 

function Work(values) { 
    this.prodID = 0; 
    this.anotherProp = 1; 

    this.updateProductID = function(newProdID) { 
     var sourceURL = "the URL here"; 
     alert("ID is: " + this.product.prodID); //displays 0 
     $.getJSON(sourceURL, function(data) { 

      //I want to update the property like this 
      this.product.prodID = data.Products.ProductID; 
     }) 
    }; 

我所試圖做的是使一個JSON調用並填充工作對象的實例的product.ProdID財產,但我總是得到this.product是不確定的。

回答

2

因爲你是一個內,你的環境的變化。這是很常見的cache你的背景,你可以通過關閉訪問的參考:

function Work(values) { 
    var self = this; 
    self.prodID = 0; 
    self.anotherProp = 1; 

    self.updateProductID = function(newProdID) { 
     var sourceURL = "the URL here"; 
     alert("ID is: " + self.product.prodID); //displays 0 
     $.getJSON(sourceURL, function(data) { 

      //I want to update the property like this 
      self.product.prodID = data.Products.ProductID; 
     }); 
    }; 
} 

的另一種方式,這可能是proxy通過jQuerys $.proxy()方法的上下文。

this.updateProductID = $.proxy(function(newProdID) { 
    // this is now pointing to the "outer" this 
}, this); 

即通過使用Javascript角.call()/.apply()方法,該方法將覆蓋this要調用的函數完成的。

0

this更換機櫃內部。你應該先儲存this像這樣:

var upper_this = this; 
this.updateProductID = function(newProdID) { 
    var sourceURL = "the URL here"; 
    alert("ID is: " + this.product.prodID); //displays 0 
    $.getJSON(sourceURL, function(data) { 

     //I want to update the property like this 
     upper_this.prodID = data.Products.ProductID; 
    }) 
}; 
相關問題