除了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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语