當您創建一個類的新實例時,構造函數方法將與您傳遞的參數一起被調用。在這個函數中,你可以使用任何代碼來構造你的類的實例,比如初始化屬性。
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()」。
特別提示:如果您未在您的子類中提供構造函數方法,則會調用父構造函數方法。