节点.js变量声明和作用域

Node.js variable declaration and scope

本文关键字:作用域 声明 变量 js 节点      更新时间:2023-09-26

当我在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 进程中的全局变量

在Chrome(或任何其他浏览器 - 好吧,我不确定旧IE...)中,无论您在示例中是否使用var都没关系,testContext将转到全局上下文,这是window

顺便说一下,"全局上下文"是 JS 中函数调用的默认this

主要区别在于 Node.js 中的所有模块(脚本文件)都在自己的闭包中执行,而 Chrome 和其他浏览器直接在全局范围内执行所有脚本文件。

全局文档中提到了这一点:

其中一些对象实际上不在全局范围内,而是在模块范围内 - 这将被注意。

您在 Node 模块中声明的var将被隔离到这些闭包之一,这就是为什么您必须导出成员以便其他模块访问它们的原因。

但是,当调用没有特定上下文的function时,它通常会默认为全局对象 - 在 Node 中方便地称为 global

function testFunction() {
    return this;
}
console.log(testFunction() === global); // true

而且,如果没有声明它的vartestContext将默认定义为全局。

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();