繁体   English   中英

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

[英]`this` in global context and inside function

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

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

$ nodejs foo.js 
object
object
is this the global object? false

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

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

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

a();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM