为什么输出是 I am inside!
function f() { console.log('I am outside!'); }
(function () {
if(false) {
// 重复声明一次函数f
function f() { console.log('I am inside!'); }
}
f();//I am inside!
}());
shike
10 years, 4 months ago
Answers
function f() { console.log('I am inside!');
这块代码是函数声明,函数声明是进入上下文时候就存在,相当于如下:
(function () {
function f() { console.log('I am inside!'); }
if(false) {
}
f();
}());
补充一点————当不是函数声明,而是函数表达式的时候:
var foo = function (){console.log('i am out')};
(function () {
if (false) {
var foo = function (){console.log('i am in')};
}
foo() // foo is not a function
}())
当为函数表达式的时候,由于var声明提前至上下文前部,相当于:
(function () {
var foo;
if (false) {
foo = function (){console.log('i am in')};
}
foo() // 此时foo为undfined,所以会报错
}())
其实我是你爸
answered 10 years, 4 months ago