我不明白为什么下面的代码返回1而不是10。你能解释一下吗?谢谢你!
var foo = 1;
function bar() {
foo = 10;
return;
function foo() { }
}
bar();
alert(foo);
由于变量提升,您的函数
function bar() {
foo = 10;
return;
function foo() { }
}
译为
function bar() {
var foo; // hoisted variable declaration
foo = 10; // now it is a number with value 10
return; // here the function stops executing
foo = function foo() { }; // now the variable *would* be a function, but this code is never reached
}
因此,全局变量不会被覆盖。
因为变量声明(以及一般的声明)是在执行任何代码之前处理,在任何地方声明一个变量在代码中相当于在顶部声明它。这也意味着变量可以在声明之前被使用。这这种行为被称为"提升",因为看起来变量声明被移到函数或全局代码的顶部。
移除function foo() { }
作品。这是通过变量提升实现的。
演示。https://jsfiddle.net/t3ehq7h7/
你能分享一下你想让函数foo()做什么吗?删除它会更新foo的值。
小提琴:https://jsfiddle.net/Ujwal_15/p8pdL134/6/
var foo = 1;
function bar() {
foo = 10;
return;
//function foo() { }
}
bar();
alert(foo);