// 定义父类
function Parent() {
this.value = 'parent value';
}
Parent.prototype.getInfo = function() {
return `Parent info: ${this.value}`;
};
// 定义子类
function Child() {
Parent.call(this); // 使用call方法调用父类构造函数,绑定this到子类实例
this.childValue = 'child value';
}
// 设置子类的原型为父类的实例,以实现继承
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// 子类重写getInfo方法,并调用父类的getInfo方法
Child.prototype.getInfo = function() {
// 使用Function.prototype.call来调用父类的getInfo方法,确保this指向子类实例
const parentInfo = Parent.prototype.getInfo.call(this);
return `${parentInfo}, Child info: ${this.childValue}`;
};
// 创建子类实例
const child = new Child();
console.log(child.getInfo()); // 输出: Parent info: parent value, Child info: child value
原理解释
- 父类定义:
- 定义
Parent
构造函数,并在其中初始化this.value
。
- 在
Parent.prototype
上定义getInfo
方法,用于获取父类信息。
- 子类定义:
- 使用
Parent.call(this)
在子类构造函数中调用父类构造函数,这样父类构造函数中的this
就会指向子类实例,从而让子类实例拥有父类定义的属性。
- 通过
Object.create(Parent.prototype)
创建一个新对象,其原型指向Parent.prototype
,并将其赋值给Child.prototype
,实现子类对父类的继承。
- 修正
Child.prototype.constructor
为Child
,因为使用Object.create
后,constructor
属性会指向Parent
。
- 子类重写方法:
- 在
Child.prototype
上重写getInfo
方法。
- 使用
Parent.prototype.getInfo.call(this)
调用父类的getInfo
方法,call
方法的第一个参数this
确保父类getInfo
方法中的this
指向子类实例,从而可以正确访问子类实例的属性。最后拼接父类和子类的信息并返回。