ใช้คำสั่ง return พร้อม this หรือ Object Literal เพื่อคืนค่าออบเจ็กต์จากฟังก์ชัน
ตัวอย่าง: Method คืนค่าสตริงจากออบเจ็กต์
<html>
<head>
<script>
var employee = {
empname: "David",
department: "Finance",
id: 002,
details: function() {
return this.empname + " with Department " + this.department;
}
};
document.write(employee.details());
</script>
</head>
</html>
ผลลัพธ์
David with Department Finance
รูปแบบการคืนค่าออบเจ็กต์
1. คืน Object Literal (Factory Function)
function createUser(name, age) {
return {
name: name,
age: age,
greet: function() {
return "Hi, I'm " + this.name;
}
};
}
var user = createUser("John", 30);
user.greet(); // "Hi, I'm John"
2. คืน this (Method Chaining / Fluent Interface)
var calculator = {
value: 0,
add: function(n) { this.value += n; return this; },
multiply: function(n) { this.value *= n; return this; },
getValue: function() { return this.value; }
};
calculator.add(5).multiply(2).add(3).getValue(); // 13
3. Constructor Function (new)
function Person(name) {
this.name = name;
this.greet = function() { return "Hi, " + this.name; };
}
var p = new Person("Alice");
p.greet(); // "Hi, Alice"
4. Class (ES6) - Syntactic Sugar
class Person {
constructor(name) { this.name = name; }
greet() { return `Hi, ${this.name}`; }
}
หมายเหตุ: ตัวอย่างต้นฉบับคืนค่า String ไม่ใช่ Object โดยตรง แต่ใช้ this เข้าถึง Property ของ Object ที่ Method อยู่