Skip to content

继承

class 继承(ES6)

javascript
class Parent {
    constructor(name, age) {
        this.name = name
        this.age = age
    }

    work() {
        console.log('Parent work')
    }
}

class Child extends Parent {
    constructor(name, age) {
        super(name, age)
    }

    run() {
        console.log('Child run')
    }
}

const son = new Child('son', 24)
console.log(son) // Child {name: 'son', age: 24}
son.work() // Parent work
son.run()  // Child run

原型链实现继承(ES5)

点击查看代码
javascript
/* 可给父类添加原型方法或属性 */
function Parent(name, age) {
    this.name = name
    this.age = age
}
Object.assign(Parent.prototype, {
    work: function() {
        console.log('Parent work')
    },

    eat: function() {
        console.log('Parent eat')
    }
})

function Child(...args) {
    /* 调用父类,改变父类中this指向为子类实例 */
    Parent.call(this, ...args)
}

// 核心思路: 将子类的原型属性指向父类的原型对象,通过js的原型链机制(向上查找)达到继承的目的

/**
 * 方法一:Object.create()
 * 该方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__
 * 该方法会重新为 prototype 属性赋值并删除 constructor 属性, 需要重新指定constructor
*/
// Child.prototype = Object.create(Parent.prototype)
// Child.prototype.constructor = Child

// 方法二:设置子类的原型属性为父类,无需手动指定子类的constructor
Object.setPrototypeOf(Child.prototype, Parent.prototype)

/* 扩展Child.prototype,可给子类添加原型方法或属性 */
Object.assign(Child.prototype, {
    run() {
        console.log('Child run')
    }
})

const girl = new Child('girl', 23)
console.log(girl) // Child {name: 'girl', age: 23}
girl.run()  // Child run
girl.work() // Parent work
girl.eat()  // Parent eat

参考资料

Updated at: