Perhaps this has already been addressed, but couldn’t find a suitable answer here. Apologies if it’s the case. Here’s the issue :
function Aclass(){
this.value1 = "a first value"
this.value2 = pulldata()
function pulldata(){
$.getJSON("data.json",function(data){
return data
})
}
}
var obj = new Aclass()
console.log(obj.value1)
console.log(obj.value2)
Result : “a first value” then “undefined”
The data var isn’t available out of the pulldata’s scope, and I’m not sure what’s the best way around this.
Your
pullData()function doesn’t actually return anything explicitly, so its return is undefined – which means what you are seeing when you log obj.value2 is correct (though undesired).Inside
pullData()you are calling$.getJSON()and passing it an anonymous function as a callback, and it is that anonymous function that returnsdatabut the return doesn’t go anywhere because the ajax call is asynchronous and the callback doesn’t occur until later.You could try this:
That is, set up your
Aclass()constructor to take a parameter that is a callback function to be executed when the class is ready, i.e., after the result from$.getJSON()is available.