模拟实现带参函数的继承--extends

120 阅读1分钟

看到其他大佬通过组合的方式模拟实现了函数的继承。我又联想到了,带参函数呢,于是,我就在此基础上做了扩展,模拟实现子类构造函数super。有不妥的地方,欢迎大家批评指正。

那么,直接上代码咯~

function Parent(name, age) {
    this.name = name
    this.age = age
    this.arr = [1,2,3,4]
}

Parent.prototype.getAge = function () {
    console.log(this.age)
}

function Child(nickName, ...args) {
    Parent.apply(this, args)
    this.nickName = nickName
}

Child.prototype = Parent.prototype
Child.prototype.constructor = Child

var child = new Child('Annie', 'Anna', 19)
var son = new Child('Timmy', 'Tim', 20)
child.arr.push(8)
console.log(child)
console.log(son)

直接上结果: