function f1() { console.log(num); var num = 10; } f1(); //此時運行結果是undefined
此時運行結果是undefined,由於預解析,變量聲明被提早了,實際按下面的方式解析的:函數
function f1() { var num console.log(num); num = 10; } f1(); //此時運行結果是undefined
舉例2:spa
//函數調用的時候,把會函數的聲明提高到做用域的上面 f1();//調用 var num = 20;//這個變量的聲明會提高到變量使用以前 function f1() { console.log(num); //var num=10; }
function f1() { console.log(num);//undefined var num = 10; } f1(); console.log(num);//報錯
<script> function f1() { console.log("哈哈"); } </script> <script> f1(); function f1() { console.log("嘎嘎"); } </script>
var a = 25; function abc() { alert(a);//undefined var a = 10; } abc(); console.log(a);//25
console.log(a); function a() { console.log('aaaaa'); } var a = 1; console.log(a);//1
預解析下的代碼解讀:code
(變量聲明在最上面,下面是函數聲明)blog
var a; function a() { console.log('aaaaa'); } console.log(a); //此時輸出的是函數a的代碼 a = 1; console.log(a);//1
代碼結果:ip
var a = 18; f1(); function f1() { var b = 9; console.log(a);//undefined console.log(b);//9 var a = '123'; }
預解析下的代碼解讀:作用域
var a; a = 18; function f1() { var b; var a; b = 9; console.log(a);//undefined console.log(b);//9 a = '123'; } f1();
代碼結果:io
f1(); console.log(c); console.log(b); console.log(a); function f1() { var a = b = c = 9; console.log(a); console.log(b); console.log(c); }
預解析下的代碼解讀:console
recap:function
function f1() { var a;//局部變量 a=9; //隱式全局變量 b=9; c=9; console.log(a);//9 console.log(b);//9 console.log(c);//9 } f1(); console.log(c);// 9 console.log(b);// 9 console.log(a);//報錯
代碼結果:class
練習4:
f1();//-----報錯 var f1 = function () { console.log(a); var a = 10; };
預解析下的代碼解讀:
var f1; f1();//-----報錯,不能調用,由於下的f1是賦值的表達式 f1 = function () { console.log(a); //f1報錯,這裏就沒有結果啦 var a = 10; };