2010-11-01 72 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; 
    }) 
}; 
相关问题