js中幾種繼承實現

繼承實現的幾種方式es6

1.藉助call實現繼承數組

function p1() {
    this.name = 'p1'
    this.say = function () {
        console.log(this.name)
    }
}
var Parent1 = p1

Parent1.prototype.show = function show() {
    console.log(this.name)
}

function Child1() {
    Parent1.call(this)
    this.type = 'c1'
}
console.log(new Child1()) // Child1 { name: 'p1', say: [Function], type: 'c1' }
/*
 * p1 {name: "p1", say: ƒ}
   name: "p1"
   say: ƒ ()
   __proto__:
   show: ƒ show()
   constructor: ƒ p1()
  __proto__: Object
 * 
 */
console.log(new Parent1()) 
View Code

這種方式ide

子類可以拿到父類的屬性值,可是問題是父類原型對象中一旦存在方法,那麼子類沒法繼承。
 
2.藉助原型鏈實現繼承
function Parent2() {
    this.name = 'p2'
    this.play = [1,2,3]
    this.say = function() {
        console.log(this.name)
    }
    this.obj = {
        habbit: '學習'
    }
}
function Child2 () {
    this.type = 'c2'
}
Child2.prototype = new Parent2()
console.log(new Child2())

var s1 = new Child2();
var s2 = new Child2();
s1.play.push(4);
console.log(s1.play, s2.play);  // (4) [1, 2, 3, 4] (4) [1, 2, 3, 4]
View Code

這種方式函數

在改變是s1的paly屬性值時,s2也會跟着變化,緣由時兩個實例使用的是同1個原型對象
這種狀況只是在數組或者對象時會發生同時變化,改變name值就不會發生變化
 
3.組合繼承 將二者結合
function Parent3() {
    this.name = 'p3'
    this.play = [1,2,3,4]
    this.say = function(){
        console.log(this.play)
    }
    this.obj = {
        news: 'sdsds'
    }
}
function Child3() {
    Parent3.call(this)
    this.type = 'c3'
}
Child3.prototype = new Parent3()
var s3 = new Child3()
var s4 = new Child3()
s3.play.push(9)
s3.obj.news = 'nff'
s3.say= function() {console.log(2222)}
console.log(s3.play, s4.play)
console.log(s3.obj.news, s4.obj.news)
s3.say()
s4.say()
View Code

這種方式學習

會多執行Child3.prototype = new Parent3() 這一句優化

 
4. 組合繼承優化
function Parent4() {
    this.name = 'p4'
    this.play = [1,2,3,4]
    this.say = function(){
        console.log(this.play)
    }
    this.obj = {
        news: 'sdsds'
    }
}

function Child4() {
    Parent4.call(this)
    this.type = 'c4'
}

Child4.prototype = Parent4.prototype

var s3 = new Child4();
var s4 = new Child4();
console.log(s3)
View Code
這種方式
將父類的原型對象直接給到子類,父類構造函數只執行一次,並且父類屬性和方法均能訪問
可是會發現,子類的構造函數居然時Parent4,這是有問題的,應該時Child4
 
5.接着優化
function Parent5() {
    this.name = 'p5'
    this.play = [1,2,3,4]
    this.say = function(){
        console.log(this.play)
    }
    this.obj = {
        news: 'sdsds'
    }
}

function Child5() {
    Parent5.call(this)
    this.type = 'c5'
}

Child5.prototype = Object.create(Parent5.prototype)
Child5.prototype.constructor = Child5
View Code

這種方式,較經常使用,固然,es6推除了class,直接繼承,就不用這麼麻煩了this

相關文章
相關標籤/搜索