用于Internet Explorer ECMAScript的Polyfill设置构造函数以允许可迭代的参数

Bre*_*ent 2 javascript ecmascript-6

我使用MDN文档中为Set对象描述的构造函数编写了一些代码。不幸的是,Internet Explorer 11忽略了构造函数中的任何可迭代参数。我快速尝试覆盖构造函数(下面的代码),但是没有运气(Set.prototype.size返回-'this'不是set对象)。

var testSet = new Set([0]);
if (testSet.size === 0) {
    //constructor doesnt take an iterable as an argument - thanks IE
    var oldProto = Set.prototype
    Set = function (iterable) {
        if (iterable) {
            iterable.forEach(this.add.bind(this));
        }
    };
    Set.prototype = oldProto;
}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以让Set构造函数传递一个可迭代的参数,并且仍然可以在IE中工作?我猜下一个最佳选择是创建某种工厂方法(Set.create),该方法将返回一个新的Set实例。

Ber*_*rgi 5

您没有Set在该代码中创建新实例。如果要覆盖构造函数,则应执行

if (new Set([0]).size === 0) {
    //constructor doesnt take an iterable as an argument - thanks IE
    const BuiltinSet = Set;
    Set = function Set(iterable) {
        const set = new BuiltinSet();
        if (iterable) {
            iterable.forEach(set.add, set);
        }
        return set;
    };
    Set.prototype = BuiltinSet.prototype;
    Set.prototype.constructor = Set;
}
Run Code Online (Sandbox Code Playgroud)