[英]Node.js variable declaration and scope
当我在node.js中键入时,我得到undefined
。
var testContext = 15;
function testFunction() {
console.log(this.testContext);
}
testFunction();
=>undefined
如果不使用var
关键字,它将通过(=> 15)。 它在Chrome控制台中运行(带有和不带有var
关键字)。
使用var
时它在Node中不起作用,因为testContext
是当前模块的本地 。 您应该直接引用它: console.log(testContext);
。
当您不输入var
,发生的情况是testContext
现在在整个Node进程中成为全局var 。
在Chrome浏览器(或任何其他浏览器中-我不确定oldIE ...),在示例中是否使用var
都没关系, testContext
将转到全局上下文 ,即window
。
顺便说一句,在“全球范围内”是默认this
在JS函数调用。
关键区别在于,Node.js中的所有模块(脚本文件)均在其自身的闭包中执行,而Chrome和其他浏览器直接在全局范围内执行所有脚本文件。
Globals文档中提到了这一点:
其中一些对象实际上不在全局范围内,而在模块范围内-请注意。
您在Node模块中声明的var
将被隔离到这些闭包之一,这就是为什么您必须导出成员以使其他模块到达它们的原因。
但是,当在没有特定上下文的情况下调用function
时,通常会将其默认为全局对象 -在Node中方便地称为global
对象 。
function testFunction() {
return this;
}
console.log(testFunction() === global); // true
并且,如果没有var
声明它,则testContext
将默认定义为global 。
testContext = 15;
console.log(global.testContext); // 15
如文件中所述
var Node.js模块内部的某些内容对于该模块而言是本地的。
因此,它会有所不同,因为var testContext
在模块上下文中,而此上下文是global
。
您也可以使用:
global.testContext = 15;
function testFunction() {
console.log(this.testContext);
}
testFunction();
我相信问题与this
关键词有关。 如果执行console.log(this)
,将看到未定义testContext。 您可能要尝试:
this.testContext = 15;
function testFunction() {
console.log(this.testContext);
}
testFunction();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.