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