ใน JavaScript Functions เป็น Objects** (First-class Objects) และสามารถเป็น Methods ของ Object** ได้ เมธอดคือฟังก์ชันที่เป็น Property ของออบเจ็กต์
การเข้าถึง Object Methods
object.methodName()
ตัวอย่าง
<html>
<head>
<script>
var employee = {
empname: "Amit",
department: "Marketing",
id: 001,
details: function() {
return this.empname + " with ID: " + this.id;
}
};
document.write(employee.details());
</script>
</head>
</html>
ผลลัพธ์
Amit with ID: 1
Functions as Objects (First-class Citizens)
ฟังก์ชันใน JS เป็น Object จริง สามารถ:
- กำหนดให้ตัวแปร:
var fn = function() {} - ส่งเป็นอาร์กิวเมนต์:
otherFunc(fn) - คืนค่าจากฟังก์ชัน:
return function() {} - มี Property/Method ของตัวเอง:
fn.name,fn.length,fn.call(),fn.apply(),fn.bind()
ตัวอย่าง Function Properties
function greet(name) {
return "Hello " + name;
}
console.log(greet.name); // "greet"
console.log(greet.length); // 1 (จำนวนพารามิเตอร์)
console.log(greet.toString()); // โค้ดฟังก์ชัน
Method Shorthand (ES6)
const obj = {
// แทน details: function() {}
details() {
return this.empname;
}
};
สรุป: ทุก Method คือ Function แต่ไม่ใช่ทุก Function เป็น Method Function กลายเป็น Method เมื่อถูกกำหนดเป็น Property ของ Object