Javascript 前端私房菜(三)-- 常用的寄生式组合继承

114 阅读1分钟

寄生:
在函数内返回对象然后调用
组合:
1、函数的原型等于另一个实例。
2、在函数中用apply或者call引入另一个构造函数,可传参.

function Parent () {
    this.name = '父亲的背影'this.arr = [1, 2, 3]
}

function Child () {
    Parent.call(this) // 借用构造函数继承
    this.type = 'son'  
}

Child.prototype = Object.create(Parent.prototype)  // 原型链继承
Child.prototype.contructor = Child
const s1 = new Child()
const s2 = new Child()

// 测试
s1.arr.push(...[4, 5])

console.log(s1.arr, s2.arr)