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
相关产品推荐
相关产品推荐

