问题描述
当我在 node.js 中输入这个时,我得到 undefined
.
var testContext = 15;函数 testFunction() {console.log(this.testContext);}测试函数();=> 未定义
没有 var
关键字,它通过 (=>15).它在 Chrome 控制台中工作(有和没有 var
关键字).
使用 var
时在 Node 中不起作用,因为 testContext
是 local of当前模块.您应该直接引用它:console.log(testContext);
.
当你不输入var
时,testContext
现在是整个Node进程中的一个全局变量..>
在 Chrome(或任何其他浏览器 - 好吧,我不确定 oldIE ...)中,在您的示例中是否使用 var
并不重要,testContext
将转到全局上下文,即window
.
顺便说一句,全局上下文"是JS中函数调用的默认this
.
When I type this in node.js, I get undefined
.
var testContext = 15;
function testFunction() {
console.log(this.testContext);
}
testFunction();
=>undefined
Without var
keyword, it passes (=>15). It's working in the Chrome console (with and without var
keyword).
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);
.
When you don't type var
, what happens is that testContext
is now a global var in the entire Node process.
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
.
By the way, the "global context" is the default this
of function calls in JS.
这篇关于Node.js 变量声明和作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!