在子类化内置函数时覆盖构造函数伪函数是否安全?

Is it safe to override the constructor pseudofunction when subclassing builtins?

在 ES6 中,我们终于可以子类化内建函数 Array:

class Bar extends Array {
    ...
}

在不做任何特殊操作的情况下,通常 return Array 个实例的 Array 方法在通过 [=14] 调用时将 return Bar 个实例=],因为他们通过 Symbol.species.

查找构造函数

现在,假设我为 Bar 定义了一个自定义构造函数。是否有任何保证如何Array的静态和成员方法调用它们通过Symbol.species查找的构造函数?简而言之,为 Array 这样的内置函数的子类提供用户定义的构造函数是否安全?

Is there any guarantee as to how static and member methods of Array call the constructor?

是的,它已正确指定并确定下来。具体来说,所有原型方法(sliceconcatmapfilter)都使用抽象ArraySpeciesCreate algorithm which will call the constructor with a single argument: an integer length. Array.of and Array.from做一些非常相似的事情,尽管后者没有当它从迭代器创建数组时传递一个长度。

concatslicefromof 也会在分配元素后显式设置 length 属性,mapfilter 没有。