javascript 如何使javascript变量全局化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11283732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make javascript variable global
提问by user123_456
I need to make this data
variable global:
我需要将此data
变量设为全局变量:
$.ajax({
url: "get_data.php",
cache: false,
dataType: 'json',
data: {},
success: function(data) {
for(var i = 0; i < data.results.length; i++) {
if(my_data.hasOwnProperty(data.results[i].id)) {
my_data[data.results[i].id].name = data.results[i].name;
}
}
});
I want to have this globally declared. Do I need to declare it as array?
我想在全球范围内宣布这一点。我需要将它声明为数组吗?
回答by Niet the Dark Absol
Any variable can be "made global" by attaching it as a property of the window.
任何变量都可以通过将其附加为窗口的属性来“设为全局”。
window.data = data;
You can now access data
as a global variable.
您现在可以data
作为全局变量访问。
回答by 0x499602D2
Set a variable equal to what you wish data
to be equal to. And when giving data
its value, reference the variable. Like this:
设置一个变量等于您希望等于的变量data
。并在给出data
其值时,引用该变量。像这样:
var obj = {};
$.ajax({
// ....
data: obj,
// ....
});