【问题标题】:Are variables defined in the global context accessible when there's name collision?当存在名称冲突时,是否可以访问在全局上下文中定义的变量?
【发布时间】:2014-06-06 16:28:53
【问题描述】:

如果我想从已经存在同名变量的范围内访问全局上下文中定义的变量:

var variable = 'value';
function someScope(variable){
    variable = 'not this';
    var global = Function('return this')();
    console.log('this > ', global.variable);
}

是否仍有可能以某种方式访问​​全局变量?

global 对象和 getting the Global object 都不起作用。 (global.variable 返回未定义)

【问题讨论】:

标签: node.js global-variables scope


【解决方案1】:

如果变量确实是全局变量,即使与局部变量发生冲突,您也可以通过 global.name 访问它。例如

// notice there is not "var" here
variable = 'global';

function someScope() {
    var variable = 'local';
    console.log(variable);            // local
    console.log(global.variable);     // global
}

someScope();

但是,如果您在文件顶部使用“var”定义变量(正如您在代码中使用的那样),那么它就不是全局的,您将得到不同的结果(即 global.variable 将打印 undefined .)

【讨论】:

    【解决方案2】:

    你可以通过window对象访问一个全局JS变量,因为每个全局变量都是window对象的一个​​属性:

    var var1 = 'Hello World!';
    
    // stated on the global scope, is the same as
    window.var1 = 'Hello World!';
    

    您还可以在函数范围内阅读这些全局变量:

    function() {
        console.log( window.var1 );
    }
    

    【讨论】:

    • 拍摄,我在 node.js 中工作(忘了提)那相当于什么?
    • 请使用搜索引擎。 Stackoverflow 不是网络词典,而是问答网站……
    猜你喜欢
    • 2015-09-27
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2013-02-25
    • 1970-01-01
    相关资源
    最近更新 更多