JavaScript:實現一個繼承

🔗 https://juejin.im/post/5c9c3989e51d454e3a3902b6


寄生組合式繼承

一般只建議寫這種,因爲其它方式的繼承會在一次實例中調用兩次父類的構造函數或有其它缺點。

核心實現

用一個 F 空的構造函數去取代執行了 Parent 這個構造函數。

function Parent(name) {
    this.name = name;
}
Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}
function Child(name, parentName) {
    Parent.call(this, parentName);  
    this.name = name;    
}
function create(proto) {
    function F(){}
    F.prototype = proto;
    return new F();
}
Child.prototype = create(Parent.prototype);
Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}
Child.prototype.constructor = Child;

var parent = new Parent('father');
parent.sayName();    // parent name: father

var child = new Child('son', 'father');
child.sayName();     // child name: son
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章