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

TypeScript继承Date类报错:TypeError: this is not a Date object

继承Date类报错的原因与解决方法

问题根源

JavaScript的原生内置对象(如Date、Array)的构造函数实现机制和普通自定义类不同。当子类继承Date时,父类的构造函数会返回一个全新的Date实例,而非初始化子类自身的this对象。这就导致你的Birthday实例本质上并不是Date对象,调用getTime()这类Date原型方法时,就会抛出TypeError: this is not a Date object.的错误。

解决方案

方案一:使用组合模式(推荐)

放弃继承Date,转而在Birthday类内部持有一个Date实例,通过封装的方式实现所需功能。这种方式避开了原生对象继承的兼容性问题,也更符合面向对象设计的"优先组合而非继承"原则。

class Birthday {
  private readonly date: Date;

  constructor(dateStr: string) {
    this.date = new Date(dateStr);
  }

  // 判断是否比另一个日期更晚(更年轻)
  public isYoungerThan(other: Date): boolean {
    return this.date.getTime() > other.getTime();
  }

  // 获取是否成年
  get isAdult(): boolean {
    const adultThreshold = new Date();
    adultThreshold.setFullYear(adultThreshold.getFullYear() - 18);
    return this.date.getTime() <= adultThreshold.getTime();
  }

  // 如需使用Date的其他方法,可按需代理
  getTime(): number {
    return this.date.getTime();
  }
}

方案二:修正原型链(不推荐,兼容性有限)

如果一定要坚持继承Date,可以在构造函数中手动修正实例的原型链,让this正确关联到Birthday的原型。不过这种方法依赖JavaScript引擎的具体实现,可能在部分环境中存在兼容性问题。

class Birthday extends Date {
  constructor(dateStr: string) {
    super(dateStr);
    // 手动将实例的原型指向Birthday的原型
    Object.setPrototypeOf(this, Birthday.prototype);
  }

  public isYoungerThan(other: Date): boolean {
    return this.getTime() > other.getTime();
  }

  get isAdult(): boolean {
    const adultThreshold = new Date();
    adultThreshold.setFullYear(adultThreshold.getFullYear() - 18);
    return this.getTime() <= adultThreshold.getTime();
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:52:22