全局上下文和内部函数中的 `this`
`this` in global context and inside function
- 在全局上下文中,
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
在Node.js中,我们在模块中编写的任何代码都将包装在一个函数中。您可以在 中阅读更多相关信息。因此,模块顶层的 this
将引用该函数的上下文,而不是全局对象。
您实际上可以使用 global
object 来引用实际的全局对象,就像这样
function a() {
console.log('is this the global object? ' + (global === this));
}
a();
- 在全局上下文中,
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
在Node.js中,我们在模块中编写的任何代码都将包装在一个函数中。您可以在 this
将引用该函数的上下文,而不是全局对象。
您实际上可以使用 global
object 来引用实际的全局对象,就像这样
function a() {
console.log('is this the global object? ' + (global === this));
}
a();