MST

星途 面试题库

面试题:JavaScript中复杂场景下原型方法与this的应用

假设有一个多层继承的JavaScript对象结构,在子类的原型方法中调用父类的原型方法,并且需要正确处理this的指向,以保证父类方法中的this在调用时指向子类实例。请编写代码实现该场景,并解释每一步的原理。
22.6万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
// 定义父类
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

原理解释

  1. 父类定义
    • 定义Parent构造函数,并在其中初始化this.value
    • Parent.prototype上定义getInfo方法,用于获取父类信息。
  2. 子类定义
    • 使用Parent.call(this)在子类构造函数中调用父类构造函数,这样父类构造函数中的this就会指向子类实例,从而让子类实例拥有父类定义的属性。
    • 通过Object.create(Parent.prototype)创建一个新对象,其原型指向Parent.prototype,并将其赋值给Child.prototype,实现子类对父类的继承。
    • 修正Child.prototype.constructorChild,因为使用Object.create后,constructor属性会指向Parent
  3. 子类重写方法
    • Child.prototype上重写getInfo方法。
    • 使用Parent.prototype.getInfo.call(this)调用父类的getInfo方法,call方法的第一个参数this确保父类getInfo方法中的this指向子类实例,从而可以正确访问子类实例的属性。最后拼接父类和子类的信息并返回。