【发布时间】:2015-01-17 20:18:09
【问题描述】:
我正在从You Don't Know JS 阅读Chapter 2: this All Makes Sense Now!,并决定做这个实验。
我有这个足够简单的脚本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()将绑定到全局对象。 - 由于
var a是在全局范围内声明的,我认为全局对象会有一个名为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 alerts 字符串 foo,正如预期的那样。
为什么 Chrome 的输出与 Node.js 不同?
【问题讨论】:
标签: javascript node.js google-chrome scope v8