在 static() 方法中使用 JavaScript 对象?
javascriptobject oriented programmingfront end technology更新于 2025/6/22 5:00:17
实际上,当我们尝试在 静态方法 中使用 对象 时,结果将是徒劳的。但是当对象作为参数发送时,我们可以访问该对象。让我们简要讨论一下。
示例 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

