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

เมธอดอื่นนอกจาก Constructor ใน JavaScript Class

เมธอด constructor() เป็นเมธอดพิเศษ ใช้ Initialize Properties เรียกอัตโนมัติเมื่อ Class ถูก Initialize หากไม่มี constructor() JavaScript จะเพิ่ม Constructor ว่างๆ ไม่มองเห็น เรายังสร้างเมธอดของตัวเองได้ โดย Syntax เหมือนเดิม

ตัวอย่าง

ในตัวอย่างนี้ แทนที่จะใช้ constructor() เริ่มต้น Properties ถูก Initialize ในเมธอดที่ผู้ใช้ตั้งชื่อว่า "anotherMet()" ผ่านเมธอดนี้ ได้ผลลัพธ์จริงตาม Output

<html> <body> <p id="method"></p> <script>    class Company {       constructor(branch) {          this.name = branch;       }       anotherMet(x) {          return x + " is the head of " + this.name;       }    }    myComp = new Company("Tesla");    document.getElementById("method").innerHTML = myComp.anotherMet("Elon musk"); </script> </body> </html>

ผลลัพธ์

Elon musk is the head of Tesla