为什么在按常规 IDE(如 visual studio 代码)编译时,`this` returns 为空对象?

Why `this` returns Empty object when Compiled on regular IDE(like visual studio code)?

在浏览器 window 中,当我在 window 上下文中记录 this 时,它会给我输出:Window 对象。 但是在这里,在正常的 IDE(如 visual studio 代码)中,当我编译它时,会给我一个空对象。为什么?以及这是如何发生的?

  console.log(this)  // in browsers output: window
// In IDE, output: {}

function test(){
    return this
}

console.log(test())  // output is global  // Why not empty

主要问题是为什么 this return 我是一个空对象,而我 运行 正常 IDE?感谢您的回答。

来自MDN

A global object is an object that always exists in the global scope.

In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables, they're created as members of the global object. (In Node.js this is not the case.) The global object's interface depends on the execution context in which the script is running. For example:

In a web browser, any code which the script doesn't specifically start up as a background task has a Window as its global object. This is the vast majority of JavaScript code on the Web. Code running in a Worker has a WorkerGlobalScope object as its global object. Scripts running under Node.js have an object called global as their global object.

在 window(浏览器)中,如果您 运行:

console.log(this === window)

它将打印 true 而如果你在节点 REPL 中 运行:

this === global

会returntrue

this 引用 console.log(this) 中的全局范围。在浏览器的情况下,它是 window,在 nodejs 的情况下,它是 Global 对象。在 vs 代码的情况下,他们将空对象作为全局对象,因为他们无力实现浏览器或 nodejs 全局对象 api 和属性。因为它是用来调试的,所以空的全局对象就足够了。