开发者

Javascript value lost across scope

开发者 https://www.devze.com 2023-04-07 08:54 出处:网络
This has been driving me mad for weeks.I have a variable data that I would like accessed at different parts of my program. Like such,

This has been driving me mad for weeks.I have a variable data that I would like accessed at different parts of my program. Like such,

var data = [];

SomeNamespace.module.method(function(){
   data.push(['some data']);
});

// data is undefined here

But, it seems to be lost, possibly 开发者_如何学Gosomething to do with scope. How can I get around this?

Thanks in advance!


That function is a callback, so data is not filled until that callback is ran.

So this:

var data = [];    
(function(){
   data.push(['some data']);
})();
data; // ['some data']

sets data, but:

var data = [];
var func = function() {
   data.push('values'); 
}
data; // [] - empty array
0

精彩评论

暂无评论...
验证码 换一张
取 消