วิธีการแบบคงที่
การใช้วิธีคงที่ เราสามารถเข้าถึงองค์ประกอบในคลาสเท่านั้น แต่ไม่สามารถเข้าถึงองค์ประกอบในวัตถุ เป็นไปได้ที่จะเรียก วิธีการแบบคงที่ เฉพาะในคลาสแต่ไม่อยู่ในวัตถุ
ตัวอย่าง-1
ในตัวอย่างต่อไปนี้ static() วิธีการเริ่มต้นในคลาส "บริษัท " แทนที่จะเป็นวัตถุ "myComp" ดังนั้นเนื้อหาใน static() เมธอดถูกดำเนินการในเอาต์พุต
<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
ในตัวอย่างต่อไปนี้ แทนที่จะเป็น คลาส อ็อบเจ็กต์ถูกเรียกดังนั้นจึงไม่มีการดำเนินการเอาต์พุต หากเราเปิดคอนโซลเบราว์เซอร์ เราจะเห็นข้อผิดพลาดที่ระบุว่า "myComp.comp() " ไม่ใช่ฟังก์ชัน
<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>