JS组合继承(combination inheritance)是一种常用的继承模式,它通过将原型链和构造函数组合使用来实现继承。
下面是JS组合继承的详细解析和代码示例:
- function Parent(name) {
- this.name = name;
- this.colors = ['red', 'green', 'blue'];
- }
- Parent.prototype.getName = function() {
- console.log(this.name);
- };
- function Child(name, age) {
- Parent.call(this, name);
- this.age = age;
- }
Child.prototype = new Parent();
Child.prototype.constructor = Child;
- Child.prototype.getAge = function() {
- console.log(this.age);
- };
- var child1 = new Child('Alice', 10);
- child1.getName(); // 输出:Alice
- child1.getAge(); // 输出:10
-
- child1.colors.push('yellow');
- console.log(child1.colors); // 输出:['red', 'green', 'blue', 'yellow']
-
- var child2 = new Child('Bob', 20);
- child2.getName(); // 输出:Bob
- child2.getAge(); // 输出:20
- console.log(child2.colors); // 输出:['red', 'green', 'blue']
在这个例子中,通过组合使用构造函数和原型链实现了继承。构造函数的继承通过在子类的构造函数中调用父类的构造函数来实现,这样就可以在子类的实例中拥有父类的属性。原型链的继承通过将子类的原型对象设置为父类的一个实例,这样就可以在子类的原型链上访问父类的方法。
需要注意的是,组合继承的缺点是在创建子类实例时调用了两次父类构造函数,一次是在Child.prototype = new Parent()这一步中,另一次是在Child.call(this, name)中。这样会导致子类的原型对象上多了一些不必要的属性,但是通过Object.create()可以解决这个问题。
总结:JS组合继承是一种常用的继承模式,它通过组合使用构造函数和原型链实现继承。虽然有一些缺点,但是它兼顾了构造函数继承和原型链继承的优点,可以有效地实现继承和方法的重用。