在static()方法中使用JavaScript对象?
实际上,当我们尝试在静态方法中使用对象 时,结果将是徒劳的。但是当对象作为参数发送时,我们可以访问该对象。让我们简要地讨论一下。
示例1
在下面的示例中,我们尝试直接使用对象“myComp”,而不是将其作为参数发送,因此,没有任何结果。如果打开浏览器控制台,将收到错误“myComp.comp()不是函数”。为了获得实际结果,我们必须将对象作为参数 发送,如例2所示。
<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>示例2
在以下示例中,对象 作为参数发送。因此我们将得到如输出所示。
<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>输出结果
Elon musk is the head of Tesla
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短