Static Methods
ใช้ Static Methods เข้าถึงเฉพาะ Elements ใน Class เท่านั้น ไม่ใช่ Elements ใน Object สามารถเรียก Static Method ได้เฉพาะภายใน Class ไม่ใช่ใน Object
ตัวอย่างที่ 1
ในตัวอย่างนี้ เริ่มต้น static() Method ใน Class "Company" ไม่ใช่ใน Object "myComp" ดังนั้น เนื้อหาใน static() ถูก Execute และแสดงใน Output
<html> <body> <p id="method"></p> <script> class Company { constructor(branch) { this.name = branch; } static comp() { return "Tutorix is the best e-learning platform" } } myComp = new Company("Tesla"); document.getElementById("method").innerHTML = Company.comp(); </script> </body> </html>
ผลลัพธ์
Tutorix is the best e-learning platform
ตัวอย่างที่ 2
ในตัวอย่างนี้ เรียกผ่าน Object แทน Class จึงไม่มี Output หากเปิด Browser Console จะเห็น Error ว่า "myComp.comp() is not a function"
<html> <body> <p id="method"></p> <script> class Company { constructor(branch) { this.name = branch; } static comp() { return "Tutorix is the best e-learning platform" } } myComp = new Company("Tesla"); document.getElementById("method").innerHTML = myComp.comp(); </script> </body> </html>