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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:38:10  来源:igfitidea点击:

How to make javascript variable global

javascriptglobal-variables

提问by user123_456

I need to make this datavariable 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 dataas a global variable.

您现在可以data作为全局变量访问。

回答by 0x499602D2

Set a variable equal to what you wish datato be equal to. And when giving dataits value, reference the variable. Like this:

设置一个变量等于您希望等于的变量data。并在给出data其值时,引用该变量。像这样:

var obj = {};

$.ajax({
    // ....

    data: obj,

    // ....
});