function t()
{
var x = 1;
if(true)
{
var x = 2;
alert(x);
}
alert(x);
}
t();
Run Code Online (Sandbox Code Playgroud)
谁知道原因?
因为JavaScript(井ECMAScript)没有块范围(尚未).只是功能范围.
实际上只有一个变量声明被提升到函数的顶部,因此x=2覆盖了初始值1.
function t()
{
var x = 1;
// v---------immediately invoked function to create a new scope
(function() {
// new variable scope
if(true)
{
var x = 2;
alert(x); // 2
}
})();
alert(x); // 1
}
t();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
143 次 |
| 最近记录: |