javaScript中實現繼承的六種方法

綜述:很經典的問題,總結下。參考鏈接:https://github.com/mqyqingfeng/Blog/issues/16

1.原型鏈繼承。

通過構建構造函數,在構造函數的原型鏈上添加屬性和方法擴展其功能。通過new 構造函數實例化,實現繼承。

function Father(){
   this.name="dad name"
}

funciton Son(){
   this.age=18;
}

Son.prototype=new Father();
var test=new Son();
test.name  //"dad name"
test.age  //18

通過上面的代碼可以看到,我們無法爲不同示例賦值不同的name,所有的實例對象只能共享一個name。

2.借用構造函數實現繼承

創建構造函數,在構造函數中使用call,bind,apply實現繼承。

function Father(){
  this.name="dad"
}
function Son(){
   Father.call(this);
}
var test=new Son();
test.name;

首先要知道apply方法的運用,它是可以更改函數的作用域,所以在上面的例子中,我們在Son子類中調用這個方法也就是將Son子類的變量在父類中執行一遍,這樣子類就擁有了父類中的共有屬性和方法。
但是,構造函數繼承也是有缺陷的,那就是我們無法獲取到父類的共有方法,也就是通過原型prototype綁定的方法。

3.組合繼承

就是原型鏈繼承和借用構造函數繼承兩種方式的組合體。這樣就能借用兩者的長處,避免短處。

// 聲明父類   
function Animal(color) {    
    this.name = 'animal';    
    this.type = ['pig','cat'];    
    this.color = color;   
}    
// 添加共有方法  
Animal.prototype.greet = function(sound) {    
    console.log(sound);   
}     
// 聲明子類   
function Dog(color) { 
    // 構造函數繼承    
    Animal.apply(this, arguments);   
}   
// 類式繼承
Dog.prototype = new Animal();   
var dog = new Dog('白色');   
dog.type.push('dog');   
console.log(dog.color); // "白色"
console.log(dog.type);  // ["pig", "cat", "dog"]

var dog2 = new Dog('黑色');  
console.log(dog2.type); // ["pig", "cat"]
console.log(dog2.color);  // "黑色"
dog.greet('汪汪');  // "汪汪"

在上面的例子中,我們在子類構造函數中執行父類構造函數,在子類原型上實例化父類,這就是組合繼承了,可以看到它綜合了類式繼承和構造函數繼承的優點,同時去除了缺陷。
可能你會奇怪爲什麼組合式繼承可以去除類式繼承中的引用缺陷?其實這是由於原型鏈來決定的,由於JavaScript引擎在訪問對象的屬性時,會先在對象本身中查找,如果沒有找到,纔會去原型鏈中查找,如果找到,則返回值,如果整個原型鏈中都沒有找到這個屬性,則返回undefined。
也就是說,我們訪問到的引用類型(比如上面的type)其實是通過apply複製到子類中的,所以不會發生共享。
這種組合繼承也是有點小缺陷的,那就是它調用了兩次父類的構造函數。

4.原型式繼承

function createObj(o) {
    function F(){}
    F.prototype = o;
    return new F();
}

就是 ES5 Object.create 的模擬實現,將傳入的對象作爲創建的對象的原型。缺點是包含引用類型的屬性值始終都會共享相應的值,這點跟原型鏈繼承一樣。

var person = {
    name: 'kevin',
    friends: ['daisy', 'kelly']
}

var person1 = createObj(person);
var person2 = createObj(person);

person1.name = 'person1';
console.log(person2.name); // kevin

person1.firends.push('taylor');
console.log(person2.friends); // ["daisy", "kelly", "taylor"]

注意:修改person1.name的值,person2.name的值並未發生改變,並不是因爲person1person2有獨立的 name 值,而是因爲person1.name = 'person1',給person1添加了 name 值,並非修改了原型上的 name 值。

5.寄生式繼承

創建一個僅用於封裝繼承過程的函數,該函數在內部以某種形式來做增強對象,最後返回對象。

function createObj (o) {
    var clone = Object.create(o);
    clone.sayName = function () {
        console.log('hi');
    }
    return clone;
}

缺點:跟借用構造函數模式一樣,每次創建對象都會創建一遍方法。

6.寄生組合式繼承

爲了方便大家閱讀,在這裏重複一下組合繼承的代碼:

function Parent (name) {
    this.name = name;
    this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.getName = function () {
    console.log(this.name)
}
function Child (name, age) {
    Parent.call(this, name);
    this.age = age;
}
Child.prototype = new Parent();
var child1 = new Child('kevin', '18');
console.log(child1)

組合繼承最大的缺點是會調用兩次父構造函數。

一次是設置子類型實例的原型的時候:

Child.prototype = new Parent();

一次在創建子類型實例的時候:

var child1 = new Child('kevin', '18');

回想下 new 的模擬實現,其實在這句中,我們會執行:

Parent.call(this, name);

在這裏,我們又會調用了一次 Parent 構造函數。

所以,在這個例子中,如果我們打印 child1 對象,我們會發現 Child.prototype 和 child1 都有一個屬性爲colors,屬性值爲['red', 'blue', 'green']

那麼我們該如何精益求精,避免這一次重複調用呢?

如果我們不使用 Child.prototype = new Parent() ,而是間接的讓 Child.prototype 訪問到 Parent.prototype 呢?

看看如何實現:

function Parent (name) {
    this.name = name;
    this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.getName = function () {
    console.log(this.name)
}
function Child (name, age) {
    Parent.call(this, name);
    this.age = age;
}
// 關鍵的三步
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
var child1 = new Child('kevin', '18');
console.log(child1);

最後我們封裝一下這個繼承方法:

function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}
function prototype(child, parent) {
    var prototype = object(parent.prototype);
    prototype.constructor = child;
    child.prototype = prototype;
}
// 當我們使用的時候:
prototype(Child, Parent);

引用《JavaScript高級程序設計》中對寄生組合式繼承的誇讚就是:

這種方式的高效率體現它只調用了一次 Parent 構造函數,並且因此避免了在 Parent.prototype 上面創建不必要的、多餘的屬性。與此同時,原型鏈還能保持不變;因此,還能夠正常使用 instanceof 和 isPrototypeOf。開發人員普遍認爲寄生組合式繼承是引用類型最理想的繼承範式。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章