除了JavaScript类中的构造函数外,还有其他方法吗?

构造函数() 方法是特殊的。这是我们初始化属性的地方。初始化类时会自动调用它。实际上,如果我们没有Constructor()方法,JavaScript 将添加一个不可见的空的Constructor() 方法。我们也可以自由地制定自己的方法。我们自己的方法的创建遵循与原始语法相同的语法。

示例

在下面的示例中,不是使用默认方法Constructor(),而是实际上在用户给定的名为“ anotherMet() ”的方法中初始化属性。通过这种方法,实际结果在输出中执行,如图所示。

<html>
<body>
<p id="method"></p>
<script>
   class Company {
      constructor(branch) {
         this.name = branch;
      }
      anotherMet(x) {
         return x + " is the head of " + this.name;
      }
   }
   myComp = new Company("Tesla");
   document.getElementById("method").innerHTML = myComp.anotherMet("Elon musk");
</script>
</body>
</html>

输出结果

Elon musk is the head of Tesla