ผลลัพธ์จะไร้ความหมายหากพยายามใช้ Object ภายใน Static Method แต่หากส่ง Object เป็น Parameter จะเข้าถึงได้ มาดูรายละเอียดกัน
ตัวอย่างที่ 1
ในตัวอย่างนี้ พยายามใช้ Object "myComp" โดยตรง แทนที่จะส่งเป็น Parameter จึงไม่ได้ผลลัพธ์ หากเปิด Browser Console จะเห็น Error ว่า "myComp.comp() is not a function" ต้องส่ง Object เป็น Parameter ตาม ตัวอย่างที่ 2
<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>
ตัวอย่างที่ 2
ในตัวอย่างนี้ ส่ง Object เป็น Parameter จึงได้ผลลัพธ์ตาม Output
<html> <body> <p id="method"></p> <script> class Company { constructor(branch) { this.name = branch; } static comp(val) { return "Elon musk is the head of " + val.name } } myComp = new Company("Tesla"); document.getElementById("method").innerHTML = Company.comp(myComp); </script> </body> </html>
ผลลัพธ์
Elon musk is the head of Tesla