WebStorm 和 console 执行的区别

Differences in execution between WebStorm and console

当运行这段代码在WebStorm中

function sayNameForAll() {
  console.log(this.name);
}

var person1 = {
  name: "Nick",
  sayName: sayNameForAll
};
var person2 = {
  name: "Greg",
  sayName: sayNameForAll
};

var name = "michael";

person1.sayName();
person2.sayName();

sayNameForAll();

打印出如下内容

Nick
Greg
undefined

但是当 运行 它在控制台中打印出来时

Nick
Greg
Michael 

造成这种差异的原因是什么?

WebStorm 运行 nodejs 中的代码。全局上下文(this)引用模块并且是一个空对象,所以属性 "name"是未定义的。

如果您在浏览器中 运行 这段代码,全局上下文(在本例中等于 window)和全局范围有些混合,因为遗留原因。

这是两种不同的环境。您可以在开头添加 "use strict" 以使您的代码以更可预测的方式运行,但仍然会有一些差异。

在浏览器中有一个window对象,脚本创建的所有变量都是属性的一个,因此在浏览器中this.name是"actually"window.name 因为 this 指的是函数范围内的 window

现在 WebStorm 运行 将这段代码当作 NodeJS 应用程序处理,这很棒,因为 WebStorm 不需要 运行 浏览器在后台运行,可以简单地使用任何节点解释器在 PATH 变量中。然而,NodeJS 没有 window 对象,所有变量都是 属性 的对象,因此它找不到 this.namethis 指的是空模块,因为您不在模块内部。