在静态 () 方法内使用 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

更新于: 2020 年 7 月 2 日

74 次浏览

职业生涯启动

通过完成课程来获得认证

开始
广告
© . All rights reserved.