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

JavaScript中如何将class类等价转换为普通function函数实现

等价实现代码

严格对齐原生class行为版本

原生class定义的原型方法默认不可枚举,且构造函数不允许直接调用必须用new关键字触发,完全对齐该特性的实现如下:

function Foo(x) {
  // 校验必须通过new调用,和原生class报错逻辑一致
  if (!new.target) {
    throw new TypeError("Class constructor Foo cannot be invoked without 'new'");
  }
  this.x = x;
}

// 给原型添加不可枚举的foo方法
Object.defineProperty(Foo.prototype, 'foo', {
  value: function() {},
  enumerable: false,
  writable: true,
  configurable: true
});

简化实现版本

如果不需要严格对齐可枚举性、new调用校验这些细节,使用更简洁的写法即可:

function Foo(x) {
  this.x = x;
}

Foo.prototype.foo = function() {};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:39:04