Javascript Closure -Local变量嵌套函数
我试图使用在函数P中定义的变量x,其值我试图在另一个函数中设置。 它总是未定义。
我试着用我的头脑来使用闭合,但它只是让我失望了。 它不会给我一个字符串而不是一个对象。
逻辑如下。
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"; } };
我已经尝试将结果dataFromQuery.query(函数(数据){存储到var然后将其设置为x,但它又作为一个对象,我需要作为一个字符串。谢谢
我想你正在寻找这样的东西:
var P = (function() { var x; function _P(i) { //your internal logic here } return _P; })();
x
和_P
都包装在机箱中,并且仅限于自动执行的匿名函数。 返回_P
并在外部作用域中以var P
提供,但x
将保持隐藏状态。