Constructor ปกติคืน this (Instance ใหม่) แต่ถ้า return Object จะคืน Object นั้นแทน (Primitive ถูกละเว้น)
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Constructor Return</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>Returning Value from Constructor</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3> Click to return object from constructor </h3>
<script>
let resEle = document.querySelector(".result");
function Human() {
this.firstName = 'Rohan';
this.lastName = 'Sharma';
this.age = 22;
return { firstName: 'Mohit', lastName: 'Sharma' }; // Return Object
}
let obj = new Human();
document.querySelector(".Btn").addEventListener("click", () => {
for (let i in obj) {
resEle.innerHTML += 'Key = ' + i + ' : Value = ' + obj[i] + '<br>';
}
});
</script>
</body>
</html>
คำอธิบาย
- Constructor กำหนด
this.firstName = 'Rohan'แล้ว - แต่
return { firstName: 'Mohit' }ทับ Instance เดิม - Instance เดิม (Rohan) ถูกทิ้ง GC
- Return Primitive (string, number, boolean, null, undefined) → ละเว้น คืน
thisตามปกติ - ใช้สำหรับ: Factory Pattern, Singleton, Object Pooling
ผลลัพธ์
Key = firstName : Value = Mohit
Key = lastName : Value = Sharma
(age และ Rohan หายไป)