Node.js变量声明和范围 [英] Node.js variable declaration and scope
问题描述
当我在node.js中输入时,我得到 undefined
。
When I type this in node.js, I get undefined
.
var testContext = 15;
function testFunction() {
console.log(this.testContext);
}
testFunction();
=>undefined
没有 var
关键字,它通过(=> 15)。它在Chrome控制台中运行(包含和不包含 var
关键字)。
Without var
keyword, it passes (=>15). It's working in the Chrome console (with and without var
keyword).
推荐答案
使用 var
时,它在Node中不起作用,因为 testContext
是当前模块的本地即可。你应该直接引用它: console.log(testContext);
。
It doesn't work in Node when using var
because testContext
is a local of the current module. You should reference it directly: console.log(testContext);
.
当你不输入 var
,会发生的是 testContext
现在整个Node进程中的全局变量。
When you don't type var
, what happens is that testContext
is now a global var in the entire Node process.
在Chrome(或任何其他浏览器中 - 好吧,我不确定oldIE ...),如果你使用 var并不重要
或不在您的示例中, testContext
将转到全局上下文,这是窗口
。
In Chrome (or any other browser - well, I'm unsure about oldIE...), it doesn't matter if you use var
or not in your example, testContext
will go to the global context, which is window
.
顺便说一下,全局上下文是默认的此
JS中的函数调用。
By the way, the "global context" is the default this
of function calls in JS.
这篇关于Node.js变量声明和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!