javascript - `this` 的默认绑定(bind)与 Chrome 浏览器和 Node.js 不同

标签 javascript node.js google-chrome scope v8

我正在阅读 Chapter 2: this All Makes Sense Now!来自 You Don't Know JS , 并决定做这个实验。

我有这个足够简单的脚本foo.js:

var a = 'foo';
var output;

// lets find a way to output strings in both
// Chrome and Node.js
if (typeof alert === 'undefined') {
    output = console.log;
} else {
    output = alert;
}

function getA() {
    return this.a;
}

var foo = getA();
output(foo);

getA() 被调用时,我期待以下事情:

  1. 由于getA的调用点在全局范围内,getA()将绑定(bind)到全局对象。
  2. 由于 var a 是在全局范围内声明的,我认为全局对象将有一个名为 a 的属性,该属性与变量 相同一个
  3. 因此,我希望 this.a 引用变量 a
  4. 因此我希望 output(foo) 打印字符串 foo

但是,当在 Node.js(非严格模式)中运行时,这是输出:

$ node foo.js
undefined

然后我将相同的脚本包含在一个简单的 HTML 页面中,并在 chrome 中加载它。

<html>
  <head>
    <script src="foo.js" type="text/javascript"></script>
  </head>
  <body>
  </body>
</html>

Chrome alert 字符串 foo,正如预期的那样。

为什么 Chrome 的输出与 Node.js 不同?

最佳答案

Since the call site of getA is in global scope, getA() will be bound to global object.

这是对我书中的 this 绑定(bind)规则的误解。调用站点的位置(又名“在全局范围内”)完全无关紧要。这是调用的方式,仅此而已。

重要的不是在哪里 getA() 发生,而是 getA() 是一个普通的普通函数调用。 THAT 决定了您将为该调用获取绑定(bind)到 this 的全局对象。

这里的其他答案是正确的...您的 Node 主程序运行的范围实际上是一个模块(函数包装),而不是真正的全局范围。

关于javascript - `this` 的默认绑定(bind)与 Chrome 浏览器和 Node.js 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27031663/

相关文章:

javascript - 从 PHP 表中选择值并将其传递到另一个 PHP 页面

javascript - Angular View 未加载

javascript - 在nodejs中向外部模块添加功能

python-3.x - 在通过 ChromeDriver 和 Selenium 通过 Python 3 执行测试时如何解决 Chrome 显示 "Aw, Snap!"页面

javascript - 如何在chrome标题栏添加图标

javascript - Chrome & IE : onpaste event not firing?

javascript - 在 Safari 中使用 PHP 清除 Cookie 的行为很奇怪

Javascript/jQuery - 将一个数字范围映射到另一个数字范围

javascript - 将我的node.js 模块集成到express.js 应用程序

javascript - Angular/Node.js : Create subdomain on aws server from code end