我正在阅读 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()
被调用时,我期待以下事情:
- 由于
getA
的调用点在全局范围内,getA()
将绑定(bind)到全局对象。 - 由于
var a
是在全局范围内声明的,我认为全局对象将有一个名为a
的属性,该属性与变量相同一个
。 - 因此,我希望
this.a
引用变量a
。 - 因此我希望
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/