如何用es5實現繼承

PsChina發表於2018-12-14

extend (繼承)

如何用 es5 實現繼承

Father.prototype = {
    eat:function(){
        console.log(this.name+' eat something.')
    }
}

function Father(name) {
    this.name = name
    this.attr = "father's attr."
}

function Super() {
    this.constructor = Child
}

Super.prototype = Father.prototype
Child.prototype = new Super() // 繼承父類的原型方法

function Child() {
    Father.apply(this, arguments) // 繼承父類的屬性
    this.attr = "child's attr"
}
複製程式碼

測試

var child = new Child('Foo')

console.log(child,child.attr)

console.log(child instanceof Child, child instanceof Father)

child.eat()

console.log(child.newAttr)

Father.prototype.newAttr = '123'

console.log(child.newAttr)

console.log(Child.prototype.constructor === Child)
複製程式碼

結果

Child { name: 'Foo', attr: 'child\'s attr' } 'child\'s attr'
true true
Foo eat something.
undefined
123
true
複製程式碼

原文連結

相關文章