Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ความแตกต่าง: var functionName = function() {} และ function functionName() {} ใน JavaScript

functionDisplayOne เป็น Function Expression ส่วน functionDisplayTwo เป็น Function Declaration ฟังก์ชัน declaration ถูกกำหนด (defined) ทันทีที่ surrounding function ถูก execute (hoisted)

ทั้งสองวิธีใช้ประกาศฟังก์ชันใน JavaScript และ functionDisplayOne เป็น anonymous function

Function Expression

functionDisplayOne(); // TypeError: functionDisplayOne is not a function (ยังไม่ได้ assign)
var functionDisplayOne = function() { 
  console.log("Hello!"); 
};
functionDisplayOne(); // "Hello!" - ทำงานได้หลัง assign

Function Declaration

functionDisplayTwo(); // "Hello!" - ทำงานได้! (hoisted ทั้งฟังก์ชัน)
function functionDisplayTwo() { 
  console.log("Hello!"); 
}

ความแตกต่างสำคัญ

ลักษณะFunction DeclarationFunction Expression
Hoistingทั้งฟังก์ชัน (name + body)แค่ตัวแปร (var hoisted, init = undefined)
Nameมีชื่อ (named)อาจเป็น anonymous หรือ named
ScopeFunction-scoped (var)ขึ้นอยู่กับ var/let/const
ใน Block (ES6+)ไม่แนะนำ (browser-dependent)OK กับ let/const (block-scoped)

Arrow Function (ES6+)

const fn = () => console.log("Hello!"); // Function expression (arrow)
// ไม่มี this, arguments, super, new.target ของตัวเอง

แนะนำ: ใช้ Function Expression (arrow/const) เพื่อความชัดเจนและหลีกเลี่ยง hoisting confusion