繁体   English   中英

Node.js变量声明和作用域

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM