1

I have a JS object that look something like this.

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

What I am trying to do is make a json call and populate the product.ProdID property of the instance of the Work Object but I always get this.product is undefined.

2 Answers 2

2

Since you are within an anonymous function, your context changes. It's very common to cache a reference of your context which you can access via closure:

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

Another way, which could be to proxy the context via jQuerys $.proxy() method.

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

That is accomplished by using Javascripts .call() / .apply() method, which overwrites the this for a called function.

Sign up to request clarification or add additional context in comments.

Comments

0

this changes inside enclosures. You should store this first like so:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.