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>热门推荐
3 修祖屋祝福语简短
10 节日祝福语幽默简短的
11 生日祝福语大全女孩简短
12 学生开心成语祝福语简短
13 新房开工吉日祝福语简短
14 同事离别祝福语简短的
15 祝福语赠言给老师简短
16 比赛结束花束祝福语简短
17 启程出发路途祝福语简短
18 文艺结婚祝福语短语简短