ทุกฟังก์ชันใน JavaScript จะมี property prototype ถูกเพิ่มโดย JavaScript engine โดยอัตโนมัติ Property นี้เป็นออบเจกต์ที่มี property constructor ชี้กลับมาที่ฟังก์ชันตัวเอง
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Function Prototypes</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; color: blueviolet; }
</style>
</head>
<body>
<h1>Function Prototypes ใน JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">คลิกที่นี่</button>
<h3>คลิกปุ่มด้านบนเพื่อเรียกเมธอด welcome ของ person1 และ person2</h3>
<script>
const resEle = document.querySelector(".result");
const BtnEle = document.querySelector(".Btn");
function PersonConstructor(fName, lName) {
this.fName = fName;
this.lName = lName;
}
PersonConstructor.prototype.welcome = function() {
return "Welcome " + this.fName + " " + this.lName;
};
const person1 = new PersonConstructor("Rohan", "Sharma");
const person2 = new PersonConstructor("Shawn", "Smith");
BtnEle.addEventListener("click", () => {
resEle.innerHTML = "person1.welcome() = " + person1.welcome() + "<br>";
resEle.innerHTML += "person2.welcome() = " + person2.welcome() + "<br>";
});
</script>
</body>
</html>
Prototype Chain (โซ่โปรโตไทป์)
person1
│
├─ fName: "Rohan"
├─ lName: "Sharma"
└─ __proto__ ──► PersonConstructor.prototype
│
├─ welcome() { ... }
├─ constructor: PersonConstructor
└─ __proto__ ──► Object.prototype
│
├─ toString()
├─ hasOwnProperty()
└─ __proto__: null
คุณสมบัติสำคัญ
constructor: ชี้กลับไปที่ Constructor Function__proto__(หรือ[[Prototype]]): ลิงก์ไปยัง prototype ถัดไปในโซ่- การค้นหา Property: ดูในออบเจกต์เองก่อน → ไป prototype → ไป Object.prototype → null
ผลลัพธ์
แสดงข้อความต้อนรับจาก person1 และ person2 ที่ใช้เมธอด welcome ร่วมกันจาก prototype