Class
Class เป็นประเภทหนึ่งของ Function แต่แทนที่จะใช้คีย์เวิร์ด 'function' ใช้คีย์เวิร์ด 'class' แทน และกำหนด Properties ภายในเมธอด constructor() เมธอด constructor() จะถูกเรียกทุกครั้งที่ Class Object ถูก Initialize
ตัวอย่างที่ 1
ในตัวอย่างนี้ สร้าง Class ชื่อ 'company' และใน constructor() กำหนดชื่อบริษัท แล้วแสดงผลลัพธ์
<html> <body> <p id="class"></p> <script> class Company { constructor(branch) { this.name = branch; } } myComp = new Company("Tutorialspoint"); document.getElementById("class").innerHTML = myComp.name; </script> </body> </html>
ผลลัพธ์
Tutorialspoint
ตัวอย่างที่ 2
<html> <body> <script> class Company { constructor(branch) { this.name = branch; } } myComp = new Company("Rk enterprises"); document.write(myComp.name); </script> </body> </html>
ผลลัพธ์
Rk enterprises