ฟังก์ชันที่สร้างใน JavaScript จะมีคุณสมบัติต้นแบบที่เพิ่มโดย JavaScriptengine เสมอ คุณสมบัติต้นแบบคืออ็อบเจ็กต์ที่มีคุณสมบัติของคอนสตรัคตามค่าเริ่มต้น ฟังก์ชัน protoype สามารถเข้าถึงได้โดย −
functionName.prototype
เมื่อวัตถุกำลังสร้างโดยใช้ตัวสร้างฟังก์ชัน คุณสมบัติต้นแบบนี้สามารถใช้เพื่อแบ่งปันวิธีการหรือคุณสมบัติระหว่างวัตถุที่สร้างโดยตัวสร้างฟังก์ชันนั้น
ต่อไปนี้เป็นรหัสสำหรับฟังก์ชันต้นแบบใน JavaScript -
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</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 in JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">Click Here</button>
<h3>Click on the above button to call the welcome method of person1 and person2 object</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
function personConstructor(fName, lName) {
this.fName = fName;
this.lName = lName;
}
personConstructor.prototype.welcome = function () {
return "Welcome " + this.fName + " " + this.lName;
};
let person1 = new personConstructor("Rohan", "Sharma");
let 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> ผลลัพธ์

เมื่อคลิกปุ่ม 'คลิกที่นี่' -
