当 运行 作为脚本时,Node.js 中的 `this` 的上下文是什么?
What is the context for `this` in Node.js when run as a script?
来自节点 REPL:
$ node
> var x = 50
> console.log(x)
50
> console.log(this.x)
50
> console.log(this === global)
true
一切都是有道理的。但是,当我有一个脚本时:
$ cat test_this.js
var x = 50;
console.log(x);
console.log(this.x);
console.log(this === global);
$ node test_this.js
50
undefined
false
出乎我的意料。
我对 REPL 的行为与脚本的不同没有真正的问题,但是在 Node 文档中它到底在哪里说了类似 "NOTE: when you run a script, the value of this
is not set to global
, but rather to ___________." 有谁知道,this
指的是什么在全局上下文中 运行 作为脚本?谷歌搜索 "nodejs this global context script" 带我到 this page 看起来很有前途,因为它描述了 运行ning 脚本的上下文,但它似乎没有提到 this
表达式的使用任何地方。我错过了什么?
在 Node.js 中,截至目前,您创建的每个文件都称为模块。所以,当你运行一个文件中的程序时,this
会引用module.exports
。你可以这样检查
console.log(this === module.exports);
// true
其实exports
只是对module.exports
的引用,所以下面也会打印true
console.log(this === exports);
// true
可能相关:Why 'this' declared in a file and within a function points to different object
来自节点 REPL:
$ node
> var x = 50
> console.log(x)
50
> console.log(this.x)
50
> console.log(this === global)
true
一切都是有道理的。但是,当我有一个脚本时:
$ cat test_this.js
var x = 50;
console.log(x);
console.log(this.x);
console.log(this === global);
$ node test_this.js
50
undefined
false
出乎我的意料。
我对 REPL 的行为与脚本的不同没有真正的问题,但是在 Node 文档中它到底在哪里说了类似 "NOTE: when you run a script, the value of this
is not set to global
, but rather to ___________." 有谁知道,this
指的是什么在全局上下文中 运行 作为脚本?谷歌搜索 "nodejs this global context script" 带我到 this page 看起来很有前途,因为它描述了 运行ning 脚本的上下文,但它似乎没有提到 this
表达式的使用任何地方。我错过了什么?
在 Node.js 中,截至目前,您创建的每个文件都称为模块。所以,当你运行一个文件中的程序时,this
会引用module.exports
。你可以这样检查
console.log(this === module.exports);
// true
其实exports
只是对module.exports
的引用,所以下面也会打印true
console.log(this === exports);
// true
可能相关:Why 'this' declared in a file and within a function points to different object