javascript - 为什么在 Node env 和 Chrome 控制台之间运行相同的代码会有所不同?

标签 javascript node.js google-chrome scope

var name = "Global";

function funcA() {
    var name = "FunA";
    return function() {
        console.log(this.name);
    }
}

funcA()();

我使用 Node 在终端上运行上面的代码并返回undefined 但在 Chrome 控制台中它将返回 Global

为什么会出现这种情况?

最佳答案

1. 在浏览器环境中运行此脚本会强制顶级 var 成为全局 window 对象的属性。然后按照MDN :

Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object , which is window in a browser.

因此在该函数内调用 console.log(this.name); 意味着 this 将是指向全局 window 对象的链接,它将具有 name 属性。 window.name 的值为“Global”。

2. NodeJS 没有 window 对象,但有 global 对象。在 NodeJS 环境中运行脚本会在两种情况下中断: (a) 作为模块运行(例如通过 node test.js)和 (b) 不作为模块运行(例如直接在 Node 控制台中) 。 第二种情况 (b) 的工作方式与浏览器相同:global 将接收 name 属性,而 this 将是指向global的链接, 因此 this.name 的值将等于 global.name 并且为“Global”。

但是第一种情况(a)是不同的,根据NodeJS doc :

Object The global namespace object.

In browsers, the top-level scope is the global scope. This means that within the browser var something will define a new global variable. In Node.js this is different. The top-level scope is not the global scope; var something inside a Node.js module will be local to that module.

因此顶级 var 只是 Node 环境中的局部变量,并且由于 global 没有 name 属性, 调用 console.log(this.name) 显示 undefined

关于javascript - 为什么在 Node env 和 Chrome 控制台之间运行相同的代码会有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47080861/

相关文章:

javascript - 在 Bootstrap 中垂直居中一组按钮

javascript - 如何计算选择 h3 的价格?

javascript - Firebase token.email_verified 变得奇怪

javascript - 将所有子文档返回到 Jade 模板

javascript - Javascript 中的 Promise {pending}、async、await

node.js - 如何从中间件获取api结果到路由

javascript - 将方法添加到 Chrome 浏览器控制台

javascript - 如何点击显示 :none element with puppeteer?

javascript - Bootstrap 4 - Flexbox 示例不起作用

javascript - 在 "isolated world"(chrome) 中运行 javascript