การเพิ่มเมธอดให้ Object
การเพิ่มเมธอดให้ JavaScript Object ง่ายกว่า Object Constructor ต้อง Assign เมธอดให้ Property ที่มีอยู่เพื่อให้ทำงานสมบูรณ์
ตัวอย่าง
ในตัวอย่างนี้ สร้าง Object Type ก่อน แล้วสร้าง Properties ของ Object เมื่อสร้าง Properties เสร็จ กำหนดเมธอดให้แต่ละ Object และเข้าถึง Properties ผ่านเมธอดตามต้องการ
<html> <body> <p id = "prop"></p> <script> function Business(name, property, age, designation) { this.Name = name; this.prop = property; this.age = age; this.designation = designation; } var person1 = new Business("Trump", "$28.05billion", "73", "President"); var person2 = new Business("Jackma", "$35.6 billion", "54", "entrepeneur"); person1.det = function() { return this.Name + " "+" has a property of net worth "+ "" + this.prop; }; person2.det = function() { return this.Name + " "+" has a property of net worth "+ "" + this.prop; }; document.write(person2.det() +" and "+person1.det()); </script> </body> </html>
ผลลัพธ์
Jackma has a property of net worth $35.6 billion and Trump has a property of net worth $28.05billion