在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
热门推荐
2 薛之谦祝福语简短
10 简短有力的结婚祝福语
11 宝宝新年祝福语大全简短
12 新年给妈妈简短祝福语
13 英文简短唯美祝福语大全
14 阳历新年祝福语大全 简短
15 對好友毕业祝福语简短
16 分手快乐祝福语简短
17 生日祝福语男孩 简短独特
18 恭喜订婚的祝福语简短