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

Sử dụng object JavaScript bên trong static method

Kết quả sẽ vô nghĩa nếu dùng object trực tiếp bên trong static method. Nhưng khi truyền object làm tham số, có thể truy cập được. Hãy cùng tìm hiểu.

Ví dụ 1: Sai - Dùng object trực tiếp

Thử dùng object "myComp" trực tiếp thay vì truyền tham số, không có kết quả. Mở console thấy lỗi "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>

Ví dụ 2: Đúng - Truyền object làm tham số

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

Kết quả

Elon musk is the head of Tesla

Giải thích: Static method thuộc về class, không phải instance. Không thể gọi instance.staticMethod(). Phải gọi Class.staticMethod(instance) và truyền instance làm tham số.