สำหรับสิ่งนี้ ให้ใช้ “ต้นแบบ” ออบเจ็กต์ JavaScript สืบทอดคุณสมบัติและเมธอดจากต้นแบบ สำหรับการเข้าถึงตัวแปร เรายังใช้ “this” ใน JavaScript ด้วย
ตัวอย่าง
function Customer(fullName){
this.fullName=fullName;
}
Customer.prototype.setFullName = function(newFullName){
this.fullName=newFullName;
}
var customer=new Customer("John Smith");
console.log("Using Simple Method = "+ customer.fullName);
customer.setFullName("David Miller");
console.log("Using Prototype Method = "+customer.fullName); ในการรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้ -
node fileName.js.
ที่นี่ ชื่อไฟล์ของฉันคือ demo79.js
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
PS C:\Users\Amit\JavaScript-code> node demo79.js Using Simple Method = John Smith Using Prototype Method = David Miller