nodejs中的Javascript全局变量和属性 - 有时会删除全局属性?

时间:2015-02-06 22:34:32

标签: javascript node.js global-variables

为什么在节点(0.10.36)中运行以下打印“未定义”?

test = 'a global property';
var test = 'a variable';
console.log(global.test);

如果省略变量声明(删除第2行),则会按预期记录“全局属性”。

如果通过global.test = 'a global property'在全局对象上显式设置了全局属性,那么它也会按预期记录。我认为这两个陈述是等价的:

test = 'foo';
global.test = 'foo';

似乎有些情况下,与隐式创建的全局属性同名的变量声明会导致该属性被删除?

(我理解使用全局变量通常是不好的做法,我试图理解nodejs在处理与全局属性和变量声明相关的代码时与各种浏览器的区别)。

2 个答案:

答案 0 :(得分:1)

在javascript中,变量声明适用于整个文件(或最里面的封闭函数定义,如果有的话):

pi = 3.14159265359;   // refers to declared variable pi
var pi;
function myFn() {
    x = 1.618034;     // refers to declared variable x
    if (...) {
        while (...) {
            var x;    // declaration only happens once each time myFn is called
        }
    }
}
x = 2.7182818;        // refers to global variable x

因此在您的示例中,第一行设置声明的变量test的值,即使语法上它​​在声明之前。但是global.test引用了尚未设置的全局变量test

答案 1 :(得分:0)

var不会自动阻止您退出全球范围。如果您在全局命名空间中使用Node(例如,在Node REPL中,我测试过它),var test仍将是全局范围的,除非您在函数中定义它。

//assign global without var
> test = 'global variable'
'global variable'
//this is still global, so it re-writes the variable
> var test = 'still global'
undefined
> test
'still global'
//if we defined test in a local scope and return it, its different
> var returnVar = function(){ var test = 'local test'; return test }
undefined
//and the global test variable is still the same
> test
'still global'
> returnVar()
'local test'
>