【问题标题】:javascipt function and var difference when compile [duplicate]编译时的javascript函数和var差异[重复]
【发布时间】:2019-12-06 03:46:30
【问题描述】:
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"}

谁能告诉我为什么?非常感谢

【问题讨论】:

标签: javascript function var


【解决方案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);

【讨论】:

  • 宁可b = 'before func declaration'; a = b;
猜你喜欢
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
相关资源
最近更新 更多