var a;
if (true) {
a = {a: 2};
function a() {}
a.ot = '9';
a = {a: 4};
console.log('1', a);
}
console.log('2', a);
哪个输出是
1 {a: 4}
2 {a: 2, ot: "9"}
谁能告诉我为什么?非常感谢
答案 0 :(得分:1)
正如@ASDFGerte指出的,this answer解释了答案,但让我从您的示例到答案中给出的示例进行一些桥接工作。
首先,让我们删除if (true)
:仅存在一个块是相关的。其次,让我们用纯字符串替换{a: ...}
。 a.ot = '9'
行也无关紧要,因此让我们删除它。所以现在我们来看看以下内容:
var a;
{
a = 'before func declaration';
function a() {}
a = 'after func declaration';
console.log('Inside block:', a);
}
console.log('Outside block:', a);
输出如下:
Inside block: after func declaration
Outside block: before func declaration
在这一点上,应该更清楚地了解the example code from this answer的应用方式。本质上,就好像代码编写如下:
var a;
{
let b = function a() {}
a = 'before func declaration';
b;
b = 'after func declaration';
console.log('Inside block:', b);
}
console.log('Outside block:', a);