Attempting to create my first JavaScript class has presented some challenges, specifically when it comes to updating a class variable. Despite hours of testing different approaches, I still can't seem to get it right!
function ClassName(productId) {
//initialize variables
this.productId = productId;
this.shop = [];
this.product = [];
//method that triggers a response. On success, {"status" : "success", "shop" : "someshop.com"} is returned
this.auth = function() {
$.ajax({
url: "http://website.com/api/auth/",
dataType: "jsonp",
success: function(data) {
authCallback(data); //utilize callback to manage response
},
error: function() {
console.log("bad auth");
}
});
}
var authCallback = function(r) {
//confirm the response with console.log(r)
this.shop = r; //no errors here
}
}
In the authCallback method, I'm assigning r
to this.shop
, however, when I check the value of this variable later on, it remains at its initial []
.
var classInstance = new ClassName(1);
classInstance.auth();
console.log(classInstance.shop); //displays []
I even experimented in the JavaScript console by executing each line consecutively after every stage was completed (waiting for the response from classInstance.auth()
and output from authCallback()
before calling console.log(classInstance.shop);
)
What am I missing? Why isn't the variable reflecting the updated value?