Javascript Closure -Local variable nested function

2019-09-15 15:40发布

问题:

This question already has an answer here:

  • Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference 6 answers

I am trying to use a variable x defined inside a function P whose value I am trying to set in another function. It always comes undefined.

I tried applying my mind to use closure but it's just going off my head. It does not gives me a string rather a object.

The logic is as follows.

function P(i){
var x;
if(i!=null){    
//this pulls the data correctly and i could see it in network tab response. 
var dataFromQuery=widgets.DATA.create({
    url:"abc/cde",
    queryTemplate :"/query"+i+ "?"
});
    //we query the data and set the value as per the logic.
     dataFromQuery.query(function(data){
         if(data[0].name){
             x=data[0].name; // this stays undefined , and i understand this is a new local variable x.Also the value is here and comes fine here so no issues with the data but i want to set it to the variable defined outside as x.
         }
     })
}
else{
    x="somehardcode";
}

};

I have tried storing the result dataFromQuery.query(function(data){ to a var and then setting it to x but it again comes as a object, which i need as a string. Thanks

回答1:

I think you're looking for something like this:

var P = (function() {
    var x;
    function _P(i) {
        //your internal logic here
    }
    return _P;
})();

Both xand _P are wrapped in the enclosure and scoped only to the auto-executed anonymous function. _P is returned and available as var P in the outer scope, but x will remain hidden.