全局和内部函数中的`this`

Mar*_*tus 5 javascript this node.js

根据MDN的这个解释:

  • 在全局上下文中,this指的是全局对象
  • 在函数上下文中,如果直接调用函数,它再次引用全局对象

然而,以下内容:

var globalThis = this;
function a() {
    console.log(typeof this);
    console.log(typeof globalThis);
    console.log('is this the global object? '+(globalThis===this));
}

a();
Run Code Online (Sandbox Code Playgroud)

...放在文件中foo.js产生:

$ nodejs foo.js 
object
object
is this the global object? false
Run Code Online (Sandbox Code Playgroud)

the*_*eye 6

在Node.js中,我们在模块中编写的任何代码都将包含在函数中.在这个详细的答案中,您可以阅读更多相关信息.因此,this在模块的顶层将引用该函数的上下文,而不是全局对象.

您实际上可以使用globalobject来引用实际的全局对象,就像这样

function a() {
  console.log('is this the global object? ' + (global === this));
}

a();
Run Code Online (Sandbox Code Playgroud)