寄生组合式继承

akino ... 2021-10-27 20:55 JS
  • 继承方式
小于 1 分钟

emmm...一直一来对继承方式都搞不懂,感觉绕来绕去的好乱,今天决定逐个突破😶。

看了各种继承方式的比较,寄生组合式继承是比较理想的,因为相对来说操作较少且弥补了寄生继承和组合继承的缺点,既可以函数复用,也不用多次调用父类构造函数。

寄生组合式继承顾名思义就是寄生式继承和组合式继承结合使用,下面以代码形式展示该继承的特点。

function Parent() {}
function Child() {}

Parent.prototype.src = 'I am from parent.';

Parent.prototype.commonFunc = function() {
    console.log('This is common.');
}

function inherit(Parent, Child) {
    var prototype = Object.create(Parent.prototype);
    prototype.constructor = Child;  // 取代:Child.prototype.constrcutor=Child
    Child.prototype = prototype;   // 取代:Child.prototype=new Person();
}

inherit(Parent, Child);

var child = new Child();
child.commonFunc(); // output: This is common.
console.log(child.src); // output: I am from parent.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20