Function Expression: กำหนดฟังก์ชันเป็นค่าของตัวแปร
ประกาศฟังก์ชันแบบไม่มีชื่อ (anonymous) แล้ว assign ให้ตัวแปร ใช้ return ส่งค่ากลับ
ตัวอย่างโค้ดเต็ม
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Function Variable</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.demo { background: skyblue; height: 20px; width: 75%; margin: 10px; padding: 10px; }
</style>
</head>
<body>
<div class="demo" data-st="John">John Smith</div>
<div class="demo" data-st="David">David Miller</div>
<div class="demo" data-st="Adam">Adam Smith</div>
<script>
var studentNames = function() {
var names = [];
$(".demo").each(function() {
names.push($(this).data('st'));
});
return names.join();
};
console.log(studentNames()); // "John,David,Adam"
</script>
</body>
</html>
วิธีรัน
บันทึกเป็น index.html แล้วเปิดด้วย Live Server
คำอธิบาย
var studentNames = function() { ... }คือ Function Expression- ฟังก์ชันเป็น first-class citizen: assign ให้ตัวแปร ส่งเป็น argument return ได้
- ต้องเรียกด้วย
studentNames()(มีวงเล็บ) เพื่อรันฟังก์ชัน $(this).data('st')อ่าน data attributedata-st
Arrow Function (ES6+)
const studentNames = () => {
return $(".demo").map((i, el) => $(el).data('st')).get().join();
};