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;
- 添加子类的原型方法</