容我小小的写个继承

164 阅读1分钟

容我小小的写个继承

之前的文章写过原型和原型链的,JS里的继承都是基于原型链的。

ES5里通过构造函数,ES6里面有 class 关键字可以用。

一个简单的利用 Object.create() 实现的 寄生组合继承

function Father (fatherSayWhat) {
    this.fatherSayWhat = fatherSayWhat
}
Father.prototype.fatherSay = function () {
    console.log('fatherSay --> ' + this.fatherSayWhat)
}

function Child (fatherSayWhat, childSayWhat) {
    Father.call(this, fatherSayWhat)
    this.childSayWhat = childSayWhat
}
//以 Father.prototype 作为 Child.prototype 的原型
Child.prototype = Object.create(Father.prototype)
//生成的原型链关系为 Child.prototype -- __proto__ --> Father.prototype
console.log(Child.prototype.__proto__ === Father.prototype) // true
//由于重写的Child的原型,所以 constructor 指向了 Father,所以这里要修正一下
console.log(Child.prototype.constructor) // Father
Child.prototype.constructor = Child

Child.prototype.childSay = function () {
    console.log('childSay --> ' + this.childSayWhat)
}

let instance = new Child('hhh', '哈哈哈')
instance.fatherSay()
instance.childSay()

ES6 里面的 class

class Father {
    constructor(fatherSayWhat){
        this.fatherSayWhat = fatherSayWhat
    }
    fatherSay(){
        console.log('fatherSay --> ' + this.fatherSayWhat)
    }
}
class Child extends Father {
    constructor(fatherSayWhat, childSayWhat){
        super(fatherSayWhat)
        this.childSayWhat = childSayWhat
    }
    childSay(){
        console.log('childSay --> ' + this.childSayWhat)
    }
}
let instance = new Child('hhh', '哈哈哈')
instance.fatherSay()
instance.childSay()

^ _ ^