ฟังก์ชันใน JavaScript สามารถกำหนดให้เป็น Property ของ Object (Method) และเรียกใช้ด้วยวงเล็บ ()
ตัวอย่าง
<html>
<head>
<script>
var employee = { 'empname': 'David' };
employee.name = function() {
return this.empname;
};
document.write(employee.name());
</script>
</head>
</html>
ผลลัพธ์
David
รายละเอียด
var employee = { 'empname': 'David' }- สร้าง Object มี Propertyempnameemployee.name = function() { ... }- กำหนด Function ให้ Propertyname(กลายเป็น Method)this.empname- ใน Methodthisชี้ไปที่ Object ที่เรียก (employee)employee.name()- เรียก Method ผ่าน Object
Method Shorthand (ES6)
const employee = {
empname: 'David',
// แทน name: function() {}
name() {
return this.empname;
}
};
การสร้าง Method แบบ Dynamic
const obj = {};
function addMethod(obj, name, fn) {
obj[name] = fn;
}
addMethod(obj, 'greet', function() {
return 'Hello ' + this.name;
});
obj.name = 'World';
obj.greet(); // "Hello World"
Binding this (สำคัญ)
const obj = {
value: 42,
getValue: function() { return this.value; }
};
const fn = obj.getValue;
fn(); // undefined (this หายไป)
const boundFn = obj.getValue.bind(obj);
boundFn(); // 42 (this ผูกไว้)
สรุป: Function กลายเป็น Method เมื่อเป็น Property ของ Object เรียกด้วย obj.method() แล้ว this จะชี้ไปที่ obj