javascript中6中繼承方式

來源:互聯網
上載者:User

標籤:script   原型式繼承   style   original   技術   cto   ack   app   another   

1. 原型鏈繼承

先回顧一下建構函式,原型和執行個體的關係:每一個建構函式都有一個原型對象,原型對象都包含一個指向建構函式的指標,執行個體都包含一個指向原型對象

的內部指標。如果我們讓原型對象等於另一個類型的執行個體,就形成了一條原型鏈。

    function SuperType() {        this.name = ‘SuperType‘    }    SuperType.prototype.sayNmae = function () {        console.log(this.name)    }    function SubType() {        this.remark = ‘SubType‘    }    SubType.prototype = new SuperType()    SubType.prototype.sayRemark = function () {        console.log(this.remark)    }    var instance1 = new SubType()    console.log(instance1 instanceof SubType)     //true    console.log(instance1 instanceof SuperType)     //true    console.log(instance1 instanceof Object)        //true

講再多都沒有一張圖來的明白   順著__proto__就是我們說的原型鏈啦。另外超類型是指SuperType,子類型是指Subtype

原型鏈的問題

    function SuperType() {        this.colors = [‘red‘,‘yellow‘,‘blue‘]    }    function SubType() {    }    SubType.prototype = new SuperType()    var instance1 = new SubType()    var instance2 = new SubType()    instance1.colors.push(‘green‘)    console.log(instance1.colors)//["red", "yellow", "blue", "green"]    console.log(instance2.colors)//["red", "yellow", "blue", "green"]

包含參考型別值的原型屬性會被所有執行個體共用,這裡在超類型中定義的colors原本是每個執行個體單獨所有的,但是由於把SuperType的執行個體作為了SubType的prototype,

colors也就成了所有SubType執行個體所共用的了,所以修改一個執行個體colors,其他的執行個體也會改變

原型鏈的另一個問題就是建立自類型執行個體時,無法向超類型的建構函式中傳值

2.借用建構函式

 

    function SuperType(name) {        this.name = name        this.colors = [‘red‘,‘blue‘,‘green‘]    }    function SubType() {        SuperType.apply(this,arguments) // 在子類型內部調用超類型    }    var instance1 = new SubType(‘Alan‘)    var instance2 = new SubType(‘Bob‘)    instance1.colors.push(‘black‘)    console.log(instance1.colors)       //["red", "blue", "green", "black"]    console.log(instance2.colors)       //["red", "blue", "green"]    console.log(instance1.name)         //Alan    console.log(instance2.name)         //Bob

 

借用建構函式最重要的一步在於,在子類型內部調用超類型的建構函式,修改了this指向,同時滿足了參數的傳遞

借用建構函式的問題

方法都在建構函式中定義,無法實現函數複用

3.組合繼承

組合繼承又叫經典繼承,解決了原型鏈和借用建構函式的問題。

 

    function SuperType(name,age) {        this.name = name        this.age = age        this.colors = [‘red‘,‘blue‘,‘green‘]    }    Object.defineProperties(SuperType.prototype,{        sayName:{            value:function () {                console.log(this.name)            },            writable:true,            configurable:true,            enumerable:true        }    })    function SubType() {        SuperType.apply(this,arguments)     //第二次調用超類型建構函式    }    SubType.prototype = new SuperType()   //第一次調用超類型建構函式    var instance1 = new SubType(‘Banks‘,22)    var instance2 = new SubType(‘Bob‘,33)    instance1.colors.push(‘black‘)    console.log(instance1.colors) //["red", "blue", "green", "black"]    console.log(instance2.colors) //["red", "blue", "green"]

組合繼承,在建構函式中定義非公用屬性,在原型中定義公用方法。

組合繼承的問題

如果說這種繼承方式還有問題的話,那就是調用了兩次超類型建構函式。 

4.原型式繼承

道格拉斯,克羅克福德(沒錯,就是那個提出穩妥對象的小夥伴)提出了原型式繼承。他的想法是藉助已有的對象建立新對象,同時不必因此建立自訂類型。

 

function object(o) {        function F() {   //相當於原型鏈繼承中的自類型建構函式        }        F.prototype = o   // 這裡的o相當於原型鏈繼承中的超類型的執行個體        return new F()    }

 

 

 

 

在object()函數內部,先建立了一個臨時性的建構函式,然後將傳入的對象作為這個建構函式的原型,最後返回了這個臨時類型的新執行個體

和原型鏈繼承有相似的地方,但是沒有超類型建構函式,並且把一系列操作放封裝在了object函數內部。從本質上講,object()對其中的對象

執行了一次潛複製

    var person = {        name:‘Nicholas‘,        age:22,        friends:[‘Shelby‘,‘Court‘,‘Van‘]    }    var anotherPerson = object(person)    anotherPerson.name = ‘Alan‘    anotherPerson.friends.push(‘Bob‘)    var yetAnoterPerson = object(person)    console.log(anotherPerson.name)         //Alan    console.log(anotherPerson.friends)      //[‘Shelby‘,‘Court‘,‘Van‘,‘Bob‘]    console.log(yetAnoterPerson.name)       //Nicholas    console.log(yetAnoterPerson.friends)    //[‘Shelby‘,‘Court‘,‘Van‘,‘Bob‘]

原型式繼承要有一個對象作為另一個對象的繼承,然後將這個對象傳遞給object函數,然後根據需求對得到的對象進行修改

但是person對象中包含friends參考型別,這裡的friends是共有的,這裡在修改(注意是修改,而不是改變)

    anotherPerson.friends = [‘Shelby‘]    console.log(anotherPerson.friends)      //["Shelby"]    console.log(yetAnoterPerson.friends)    //[‘Shelby‘,‘Court‘,‘Van‘,‘Bob‘]

上面的代碼我們改變了anotherPerson的friends,這裡會在anotherPerson執行個體中添加一個friends屬性,並不會改動,person中的friends

原型鏈繼承中也是一樣的道理

原型式繼承的問題

原型式繼承建立的對象,相當於傳入對象的副本,和原型鏈繼承的問題一樣,每個執行個體沒有自訂的屬性。而且原型式繼承進行的是淺複製,無法用instanceof操作符檢測。

關於instanceof操作符與原型鏈 參考這一篇

https://www.cnblogs.com/flawlessBlithe/p/8515435.html

5.寄生式繼承

寄生式繼承的思路與寄生建構函式和原廠模式類似,即建立一個僅用於封裝繼承過程的函數,該函數在內部以某種方式來增強對象,最後再返回對象。

 

function createAnother(original) {        var clone = object(original)        clone.sayHi = function () {    // 以某種方式增強對象 返回執行個體之前給執行個體添加方法            console.log(‘hi‘)        }        return clone    }

 

寄生式繼承的問題

寄生式繼承解決了原型式繼承無法自訂方法的問題,但是依然是進行的淺複製,無法進行instanceof操作符檢測

6.寄生組合式繼承

看名字大家就想到了,寄生組合式繼承為的就是解決,寄生式繼承無法進行instanceof操作符檢測的問題,以及組合式繼承調用了兩次超類型建構函式的問題。

function object(o) {    function F() {   //相當於原型鏈繼承中的子類型建構函式    }    F.prototype = o   // 這裡的o相當於原型鏈繼承中的超類型的執行個體    return new F()}function SuperType(name,age) {    this.name = name    this.age = age}SuperType.prototype.sayName = function () {    console.log(this.name)}function SubType() {    SuperType.apply(this,arguments)}// 下面這個函數做的操作為的是解決組合繼承中第二次調用超類型建構函式的問題// 即這一步 SubType.prototype = new SuperType()function inheritPrototype(SubType,SuperType) {    var n = object(SuperType.prototype)   //對超類型的原型進行淺複製    n.constructor = SubType    // 如果沒有這一步後面將無法使用instanceof檢查是不是SubType的執行個體    /*  上面的操作是使用原型式繼承的方式 創造一個SuperType.prototype的副本        也就是替換 new Supertype() 這一步     */   console.log( n.__proto__ === SuperType.prototype )// true    console.log(n instanceof SuperType)  //true    SubType.prototype = n}inheritPrototype(SubType,SuperType)SubType.prototype.sayAge = function () {  // 這裡在prototype中添加sayAge方法已經是添加在了 inheritPrototype 函數內部的n上    console.log(this.age)}var instance = new SubType(‘Alan‘,23)console.log(instance instanceof SubType) //trueconsole.log(instance instanceof SuperType) // true

寄生組合式繼承 比較難理解的那裡應該是解決第二次調用超類型建構函式的部分。

聽說寄生組合式繼承還有問題。。。。。 應該是 太麻煩了  哈哈哈

 

 

javascript中6中繼承方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.