Javascript中的全局variables和nodejs中的属性 – 全局属性有时会被删除?

为什么在节点(0.10.36)中运行时打印“undefined”?

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

如果省略了variables声明(删除第2行),则会按预期方式logging“全局属性”。

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

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

它几乎看起来像某种情况下,与隐式创build的全局属性具有相同名称的variables声明导致该属性被删除?

(我明白全局使用通常是不好的做法,我想了解nodejs在处理与全局属性和variables声明相关的代码时如何与各种浏览器不同)。

在JavaScript中,variables声明适用于整个文件(或最内层的函数定义,如果有的话):

 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 

因此,在你的例子中,第一行设置声明的variablestest的值,尽pipe它在语句之前是语法的。 但是global.test指的是没有设置的全局variablestest

var不会自动将你排除在全局范围之外。 如果你在全局命名空间中的Node中工作(比如在Node REPL中,我testing了这个) 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' >