权威指南3.10.1中提到了关于javascript函数作用域中声明提前的原理,但是为了理解透彻,这里我做了多个测试。
Test1:
var scope='global';
function f(){
scope='local';
console.log('scope='+scope);
var scope;
};
f();
var scope='global';
function f(){
scope='local';
console.log('scope='+scope);
var scope;
};
f();结果: scope=local
Test2:
var scope='global';
function f(){
console.log('scope='+scope);
var scope='local';
};
f();
var scope='global';
function f(){
console.log('scope='+scope);
var scope='local';
};
f();结果:
scope=undefined
两个测试可以说明:
在javascript函数中声明提前的过程是执行函数时,先找出声明语句var xx;
然后再从函数的第一行开始执行。即所谓声明提前。
var scope='global';
function f(){
scope='local';
console.log('scope='+scope);
var scope;
};
f();
var scope='global';
function f(){
scope='local';
console.log('scope='+scope);
var scope;
};
f();
317

被折叠的 条评论
为什么被折叠?



