思路

  • 创建一个空对象空对象的原型链接到父类显式原型
  • 空对象constructor指向子类
  • 子类的显式原型指向空对象

代码

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @description 寄生组合继承
* @params childClass - 子类,parentClass - 父类
*/
function inherit(Child, Parent) {
// 创建一个`空对象`,`空对象`的原型链接到`父类`的`显式原型`上
const obj = Object.create(Parent.prototype)
// `空对象`的`constructor`指向`子类`
obj.construct = Child
// 子类的显式原型指向`副本对象`
Child.prototype = obj
}
  • 使用示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function Person(name) {
this.name = name
this.colors = ['red', 'blue', 'green']
}
Person.prototype.sayName = function () {
console.log(this.name)
}

function Student(name, age) {
// 调用父类函数构造函数
Person.call(this, name)
this.age = age
}

// 寄生式组合继承
inherit(Student, Person)
// 子类方法必须在继承之后设置
Student.prototype.sayAge = function () {
console.log(this.age)
}

const stu = new Student('violet', 20)
console.log(stu)
stu.sayName()
stu.sayAge()