在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