You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在未知对象类型时访问其静态成员,继承子类静态重写逻辑?

解决实例方法访问子类重写静态成员的问题

问题分析

原代码中instanceLikesFood直接硬引用BaseClass.likedFoodsByType,导致子类实例调用该方法时,始终使用父类的静态数组,无法获取子类重写后的likedFoodsByType,因此childObj.instanceLikesFood("burritos")返回false。

解决方案

利用实例的constructor属性获取其所属的类(子类实例的constructor指向子类本身),并复用父类定义的静态方法typeLikesFood——该方法中的this会自动绑定到当前类(子类调用时即为ChildClass),从而间接访问子类重写的静态成员。

修正后的完整代码

class BaseClass {
    private static likedFoodsByType = ["tacos"];

    constructor(private readonly individualLikes: string[]) {}

    public static typeLikesFood(food: string): boolean {
        return !!this.likedFoodsByType.includes(food); // 改用includes更准确,find需传入回调函数
    }

    public instanceLikesFood(food: string): boolean {
        // 通过constructor获取实例所属类,调用其静态方法
        const currentClass = this.constructor as typeof BaseClass;
        return currentClass.typeLikesFood(food) || this.individualLikes.includes(food);
    }
}

class ChildClass extends BaseClass {
    private static override likedFoodsByType = [...super.likedFoodsByType, "burritos"];
}

const childObj = new ChildClass(["enchiladas"]);
console.log(childObj.instanceLikesFood("burritos")); // 输出true

关键点说明

  1. constructor属性:每个实例的constructor指向创建它的类,子类实例的constructor就是ChildClass,而非BaseClass。
  2. 静态方法的this绑定:静态方法中的this指向调用该方法的类,因此currentClass.typeLikesFood(food)会使用子类重写的likedFoodsByType。
  3. 类型断言:TypeScript中需要将this.constructor断言为typeof BaseClass,才能正确调用静态方法typeLikesFood。
  4. 方法替换:原代码中find(food)写法错误(find需接收回调函数),改用includes直接判断元素是否存在更符合需求。

内容的提问来源于stack exchange,提问作者jordaniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 08:32:16