现在最先的行为准则:js变量申明必须带var;然后开始随笔:
函数中的变量申明在编译的时候都会提到函数开头。
例如:
1 function foo(){ 2 console.log('some code here'); 3 var a=1; 4 console.log('other code here'); 5 }
实际上等价于:
1 function foo(){ 2 var a; 3 console.log('some code here'); 4 a=1; 5 console.log('other code here'); 6 }
另外一点补充,关于函数传参缺省:
1 function foo( a ){ 2 if( typeof a === 'undefined' ) a=1; // 给a附初始值 3 console.log('code with a'); 4 } 5 foo(); //调用 不传参
我之前有个误区,先上有误区的代码吧:
1 function foo( a ){ 2 if( typeof a === 'undefined' ) var a=1; // 给a附初始值 3 console.log('code with a'); 4 }
上面这段相对于之前的多一个申明,代码是正确的,误区在于:我以为在foo()这样调用的时候,a没有申明。
事实是 第一行函数申明中的参数就是申明,而且如果没有申明,第二行的判断语句是会抛出异常的。