当您创建一个类的新实例时,构造函数方法将与您传递的参数一起被调用。在这个函数中,你可以使用任何代码来构造你的类的实例,比如初始化属性。
class Person{
constructor(name){
this.name = name;
}
sayHi(){
alert(`${this.name} says hello!`);
}
}
let person = new Person('Jerry');//this param will be send to the constructor method
person.sayHi();
该代码的结果将是一个警报,说“杰里说你好!”。
虽然,构造函数方法不是必需的。以下代码也可以工作。
class Person{
sayHi(){
alert("Someone says hello!");
}
}
let person = new Person();
person.sayHi();
如果您有一个子类,您可能需要调用父类的构造方法。这也不是必需的,但在大多数情况下会完成。
class Person{
constructor(name){
this.name = name;
}
sayHi(){
alert(`${this.name} says hello!`);
}
}
class SophisticatedPerson extends Person{
constructor(name){
super(name);//this will call the constructor method of the Person class
}
sayHi(){
alert(`${this.name} says: Top of the hat to you, sir!`);
}
oldSayHi(){
super.sayHi();//call sayHi of the Person class
}
}
let person = new SophisticatedPerson('Jerry');
person.sayHi();//calls the overidden sayHi method of SophisticatedPerson class
person.oldSayHi();//calls the oldSayHi of SophisticatedPerson class which calls sayHi of Person class
与父类如上所示的“超级”您可以通过调用构造“超级()”或通过任何其它方法“super.methodName()”。
特别提示:如果您未在您的子类中提供构造函数方法,则会调用父构造函数方法。