Featured image of post 【JavaScript 函式】function expression(函式陳述式) VS declaration (函式運算式)

【JavaScript 函式】function expression(函式陳述式) VS declaration (函式運算式)

【JavaScript 函式】function expression(函式陳述式) VS declaration (函式運算式)

Photo by Mohammad Rahmani on Unsplash

declaration (函式運算式)

function declarationFunction(){
	console.log(123);
}

declarationFunction();

function expression (函式陳述式)

let expressionFunction = function(){
	console.log(123);
}

expressionFunction();

差異

提前使用 function

declaration (函式運算式) 因為 hoisting 提升 的關係,所以可以順利執行

declarationFunction();

function declarationFunction(){
    // 123
    console.log(123);
}

expression (函式陳述式) 則是因為變數尚未未宣告內容,所以無法執行

// ReferenceError: Cannot access 'expressionFunction' before initialization
expressionFunction();

let expressionFunction = function(){
    console.log(123);
}

記憶體回收機制

declaration (函式運算式)

  • 只要被定義過後就無法從記憶體中刪除並回收

expression (函式陳述式)

  • 正常的跟著變數生命週期運作, 所以可能定義完後則直接被回收或是跟著變數的參考被移除時就結束等待 Garbage Collection 回收

正常回收記憶體

declaration (函式運算式) 直接被回收

// declaration (函式運算式)直接被回收
(function(val){
    console.log(val);
})(123);

expression (函式陳述式) 變數設定為 null 被回收

let expressionFunction=function(){
    console.log(123);
}

expressionFunction();
expressionFunction=null;
// expressionFunction is not a function
expressionFunction();

參考資料

Donate KJ 贊助作者喝咖啡

如果這篇文章對你有幫助的話,可以透過下面支付方式贊助作者喝咖啡,如果有什麼建議或想說的話可以贊助並留言給我
If this article has been helpful to you, you can support the author by treating them to a coffee through the payment options below. If you have any suggestions or comments, feel free to sponsor and leave a message for me!
方式 Method 贊助 Donate
PayPal https://paypal.me/kejyun
綠界 ECPay https://p.ecpay.com.tw/AC218F1
歐付寶 OPay https://payment.opay.tw/Broadcaster/Donate/BD2BD896029F2155041C8C8FAED3A6F8
All rights reserved,未經允許不得隨意轉載
Built with Hugo
Theme Stack designed by Jimmy