<script type="text/javascript">
function star(){
function end(){
console.log(c);
}
var c=8;
end();
}
star();
</script>
为什么console.log(c)
还是会弹出8,明明函数声明在c=8赋值之前,难不倒执行的时候,函数跑到了c=8的后面了么?
建议你先读读var hoisting
你上述的代码在js执行引擎解释时,其实是这个样子:
function star() {
var c;
function end() {
console.log(c);
}
c = 8;
end();//注意这里,当你调用end方法时,c已经赋值为8了
}
star();
你是说,end()执行后,还能弹出8?你的问题,不是和执行环境有关。而是声明函数的方式。你的是函数声明式:
函数声明:代码执行之前,解析器就已经读取函数声明并将其添加到执行环境中,因此你的代码可以正常运行。
以上是我之前的回答,也许我没了解清楚。
我又仔细看了看你的代码,
<script type="text/javascript">
function star(){
function end(){
console.log(c);
}
var c=8;//在end()执行前,你已经声明好变量c,并赋值。
end(); //执行时,当然能够找到局部变量c,并成功弹出8。
}
star();
</script>
如果先执行,在声明就会返回undefined
<script type="text/javascript">
function star(){
function end(){
console.log(c);
}
end(); //执行时,未找到变量c,返回undefined。
var c=8;//在end()执行后声明,并没有用。
}
star();
</script>
执行end()的时候c已经赋值了
end();
function end(){
console.log(c);
}
var c=8;
}
这样c是undefined
因为你在调用end函数之前已经声明c了
变量c和函数end()拥有同样的作用域
函数end()调用时,变量c已经赋值