ES6 子类数组不带类



出于兴趣,是否可以通过旧的原型方法对Array进行子类化?如果有任何引擎支持,理论上像下面这样的东西会起作用吗?

function SubArray() {
    super();
}
SubArray.prototype = Object.create(Array.prototype);
SubArary.prototype.constructor = SubArray;
SubArray.prototype.forEachRight ...

不,这是不可能的。不仅因为super()不完全是"旧原型方法",还因为它不允许在构造函数之外:

§14.1.2 静态语义:函数声明和表达式的早期错误

如果 FunctionBody Contains SuperCall true,则为语法错误。

您需要调用Array作为构造函数,因此Array.call(this, …)不起作用(与在 ES5 中不起作用的方式相同)。但是,由于Reflect对象,应该可以伪造super()构造函数调用。我们将使用Reflect.construct

function SubArray() {
    return Reflect.construct(Array, [], SubArray)
}
…

请注意,您需要执行以下操作:

function SubArray() {
    …
}
Reflect.setPrototypeOf(SubArray, Array);
Reflect.setPrototypeOf(SubArray.prototype, Array.prototype);

以匹配新的class语义,而不是执行SubArray.prototype = Object.create(Array);.

最新更新