Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เพิ่มเมธอดให้ JavaScript Object Constructor

การเพิ่มเมธอดให้ Object Constructor แตกต่างจากการเพิ่มเมธอดให้ Normal Object ไม่สามารถเพิ่มเมธอดแบบปกติได้ ต้องเพิ่มเมธอด ภายใน Object Constructor เอง

ตัวอย่าง

ในตัวอย่างนี้ เมธอด ถูกเพิ่มภายใน Constructor จึงได้ค่าที่ถูกต้อง

<html> <body> <script>    function Business(name, property, age, designation) {       this.Name = name;       this.prop = property;       this.age = age;       this.designation = designation;       this.name = function() {          return this.Name       };    }    var person1 = new Business("Trump", "$28.05billion", "73", "President");    document.write(person1.name()); </script> </body> </html>

ผลลัพธ์

Trump