Javascript 如何从$.getJSON()调用访问自定义JS对象?

Javascript 如何从$.getJSON()调用访问自定义JS对象?,javascript,jquery,Javascript,Jquery,我有一个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"; a

我有一个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属性,但我总是得到这个结果。product是未定义的

在机柜内部发生变化。您应该先存储此,如下所示:

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

由于您在一个
匿名函数中
,因此您的上下文会发生变化。
缓存
您可以通过闭包访问的上下文引用是非常常见的:

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;
        });
    };
}
另一种方法是通过jQuerys
$.proxy()
方法代理上下文

this.updateProductID = $.proxy(function(newProdID) {
    // this is now pointing to the "outer" this
}, this);
这是通过使用Javascripts
.call()
/
.apply()
方法实现的,该方法覆盖被调用函数的
this