寄生组合式继承是指利用原型链实现对原型属性和方法的继承,并且通过借用构造函数来实现对实例属性的继承。在js中,使用寄生组合式继承的方法如下:
1. 定义一个父类,并且定义一个构造函数,用来接收参数。
function Parent(name) {
this.name = name;
}
2. 定义父类的原型方法,用来实现父类的方法继承。
Parent.prototype.getName = function() {
return this.name;
}
3. 定义子类,并且定义一个构造函数,用来接收参数。
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
4. 定义子类的原型方法,用来实现子类的方法继承。
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.getAge = function() {
return this.age;
}
5. 创建子类的实例,并且调用子类的方法。
var child = new Child('John', 18);
console.log(child.getName()); // John
console.log(child.getAge()); // 18
以上就是js中使用寄生组合式继承的方法,它可以有效地实现原型和实例的继承,从而提高代码的复用性。