除了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
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬