this引用全局对象然而,以下各点:
var globalThis = this;
function a() {
console.log(typeof this);
console.log(typeof globalThis);
console.log('is this the global object? '+(globalThis===this));
}
a();..。放置在文件foo.js中会产生:
$ nodejs foo.js
object
object
is this the global object? false发布于 2015-09-24 11:17:27
在Node.js中,我们在模块中编写的任何代码都将封装在一个函数中。您可以在这个detailed answer中读到更多关于这个的内容。因此,模块顶层的this将引用该函数的上下文,而不是全局对象。
实际上可以使用 object来引用实际的全局对象,如下所示
function a() {
console.log('is this the global object? ' + (global === this));
}
a();https://stackoverflow.com/questions/32759892
复制相似问题