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

Babel转译类继承异常:Firefox 43中test方法调用报错

Babel转译类继承在Firefox 43中的兼容问题解决

问题场景

原始代码:

class Test1 {
    emit() {
        console.log(2)
    }
}

class Test extends Test1 {
    test() {
        console.log(1);
    }
}

const a = new Test();
a.test()

这段代码经Babel转译后,在现代浏览器运行正常,但在Firefox 43中抛出错误:

TypeError: a.test is not a function

问题根源

  • Babel会根据目标环境支持情况,将类继承转译为Reflect.construct(当环境支持Reflect时)或传统上下文绑定逻辑
  • Firefox 43中的Reflect.construct(Super, arguments, NewTarget)存在bug,会忽略NewTarget的原型,导致子类方法无法挂载到实例上
  • 类似的Reflect.construct兼容性问题在Closure Compiler的brokenConstruct相关代码中也有记录,对应早期JS引擎的原型处理缺陷

解决步骤

1. 修正Babel目标环境配置

确保你的Babel preset-env配置明确包含Firefox 43,让Babel自动检测该环境的Reflect.construct bug,生成兼容的转译代码:

{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "firefox": "43"
      }
    }]
  ]
}

当Babel检测到Firefox 43时,会放弃使用Reflect.construct,转而使用传统的原型链继承逻辑,避免触发该bug。

2. 强制禁用Reflect.construct转译

如果上述配置不生效,可以手动添加@babel/plugin-transform-classes插件,并设置loose模式,强制生成基于原型链的继承代码:

{
  "plugins": [
    ["@babel/plugin-transform-classes", {
      "loose": true
    }]
  ]
}

loose模式下,类继承会通过直接设置prototype和__proto__来实现,绕过Reflect.construct,从而兼容Firefox 43。

3. 手动补全原型链(应急方案)

如果无法修改Babel配置,可以在代码中手动修复实例的原型链:

const a = new Test();
// 手动将Test的原型挂载到实例上
Object.setPrototypeOf(a, Test.prototype);
a.test();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:54:40