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 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短