2016-03-07 37 views
2

我正在學習ES2015的過程中,並沒有完全理解有關類的所有內容。據我瞭解,你像這樣定義一個類:在ES2015中定義一個類,什麼是構造函數方法,爲什麼它很重要?

class Parent { 
    constructor() { 
    // ... 
    } 
} 

和這樣的一個子類: (其中超()必須被調用,以最初運行從父類的構造函數)。

class subClass extends Parent { 
    constructor(name, description, url) { 
    // subclass must call super to invoke the parent's constructor method 
    super(); 
    } 
} 

到底是什麼類的構造方法,它爲什麼重要?爲什麼一個家長的構造需要創建一個子類的實例時被調用?

回答

2

當您創建一個類的新實例時,構造函數方法將與您傳遞的參數一起被調用。在這個函數中,你可以使用任何代碼來構造你的類的實例,比如初始化屬性。

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()」。

特別提示:如果您未在您的子類中提供構造函數方法,則會調用父構造函數方法。

2

構造函數方法是當您使用關鍵字new構造對象時調用的方法。它用於初始化對象的基本屬性。

您必須調用父構造函數的原因(除了簡單的事實,即「語言規則」是如何定義的),您需要允許父類進行初始化。

這些是許多OOP語言中相當基本的常見概念。

相關問題