Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Static method trong class JavaScript

Static methods

Dùng static method chỉ truy cập được element trong class, không phải object. Chỉ gọi static method bên trong class, không gọi từ object.

Ví dụ 1: Gọi đúng từ class

<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>

Kết quả

Tutorix is the best e-learning platform

Ví dụ 2: Sai - Gọi từ object

<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>

Lỗi console: "myComp.comp() is not a function"

Tóm tắt:

  • Static method: Class.method() ✓ | instance.method() ✗
  • Dùng cho utility function, factory method, không cần state instance
  • Không truy cập được this instance (this = class constructor)
  • Kế thừa: class con cũng kế thừa static method cha