javascript中的ES6 Set子类

Subclassing ES6 Set in javascript

本文关键字:子类 Set ES6 中的 javascript      更新时间:2023-09-26

我在尝试从ecmascript 6中可用的新Set继承时遇到了问题。该类定义如下:

function SelectionManager () {
  Set.call(this);
}
SelectionManager.prototype = Object.create(Set.prototype);
SelectionManager.prototype.add = function (unit) {
  unit.setIsSelected(true);
  Set.prototype.add.call(this, unit);
};
/* Some functions left out */

当尝试调用add时,我得到以下错误:TypeError: Set operation called on non-Set object

代码可在http://jsfiddle.net/6nq1gqx7/

ES6的草案明确指出,应该可以对Set进行子类化,正确的方法是什么?

看起来这是被跟踪的:

https://github.com/google/traceur-compiler/issues/1413

目前没有正确的方法。Chrome/V8(和大多数其他浏览器一样)还不能正确地支持内建的子类化——部分原因是它的实现可能相当复杂,部分原因是精确的语义仍在不断变化,并且在最近的ES6会议上刚刚被推翻,目前还没有最终解决方案(截至2014年10月)。

在Chrome、Firefox和Edge(但不是IE11)中,您可以使用此解决方法将ES6子类Set and Map:

class MySet extends Set {
  constructor() {
    // instead of super(), you must write:
    const self = new Set();
    self.__proto__ = MySet.prototype;
    return self;
  }
  // example method:
  add(item) {
    console.log('added!')
    super.add(item); // Or: Set.prototype.add.call(this, item);
  }
}
var mm = new MySet();
console.log(mm.size); // logs 0
mm.add(5);            // logs 'added!'
console.log(mm.size); // logs 1