JavaScript类中的静态方法?
静态方法
使用静态方法,我们只能访问类中的元素,而不能访问对象中的元素。可以仅在类内部而不在对象中调用静态方法。
示例1
在以下示例中, static()方法在类“Company”中而不是在对象“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
在下面的示例中,将调用对象,而不是class,因此将不执行任何输出。如果打开浏览器控制台,则会看到错误,指出“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>