201207241213JavaScript named function expression
在講 named function expression 前,要先釐清 function expression 和 function declaration 。
如果在宣告函式的同時將 function reference 丟出, assign 給另一個變數,或是傳入另一個函式,是 function expression 。例:
var f = function() { alert('f'); }
或
setTimeout(function() { alert('f') }, 1000);
反之則是 function declaration 。例:
function f() { alert('f'); }
function declaration 不論宣告位置為何,在函式內 scope 和父 scope 都可以存取到函式:
alert(typeof f); // function f(); // function function f() { alert(typeof f); } alert(typeof f); // function f(); // function
function expression 則要在 assign 給變數後才可存取:
alert(typeof f); // undefined var f = function() { alert(typeof f); } alert(typeof f); // function f(); // function
有了以上認識後,再回到主題 named function expression ,也就是 function expression 也是可以給予名稱的,而這個名稱只有函式內存取得到:
alert(typeof f); // undefined alert(typeof g); // undefined var f = function g () { alert(typeof f); // function alert(typeof g); // function } alert(typeof f); // function alert(typeof g); // undefined f();
但 IE 例外, IE named function expression 函式外也存取得到,直到 IE 10 問題才修正:
var f = function g() { alert(typeof f); alert(typeof g); // function } alert(typeof f); // function alert(typeof g); // function f(); g(); /* IE only, except IE 10 */
回應