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>热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短