错误代码:
function functions(flag){
if (flag) {
function getValue() { return 'a'; }
} else {
function getValue() { return 'b'; }
}
return getValue();
}
上述代码永远输出b
错误原因:
因为js没有块级作用域,加上函数声明提前,所以相当于:
function functions(flag){
function getValue() { return 'a'; }
function getValue() { return 'b'; }
if (flag) {
..
} else {
..
}
return getValue();
}
返回的方法为重写后的方法
改正方法:
function functions(flag){
if (flag) {
var getValue=function getValue() { return 'a'; }
} else {
var getValue=function getValue() { return 'b'; }
}
return getValue();
}