从Set.prototype继承 [英] Inheriting from Set.prototype
问题描述
这真的是我的错误。我可以轻松地创建一个继承自 Array.prototype
的方法的新类:
This is really bugging me. I can easily create a new class that inherits methods from Array.prototype
:
var MyArray = function() {};
MyArray.prototype = Array.prototype;
var myArray = new MyArray();
myArray.push(1); // this is allowed
同样的继承模式似乎不适用于 Set.prototype
:
The same inheritance pattern doesn't seem to work with Set.prototype
:
var MySet = function() {};
MySet.prototype = Set.prototype;
var mySet = new MySet();
mySet.add(1); // TypeError: Method Set.prototype.add called on incompatible receiver
这是一个实现问题?还有另一种继承格局吗?我已经在节点v0.12和金丝雀中尝试了相同的结果。
Is this an implementation issue? Is there another inheritance pattern that will work? I've tried this in node v0.12 and Canary with the same results.
编辑:这个解决方案有效,但是我仍然不知道为什么上面的t工作相同:
This solution works, but I'm still not sure why the above doesn't work the same:
var MySet = function(array) {
var inst = new Set(array);
inst.__proto__ = MySet.prototype;
return inst;
}
MySet.prototype = Object.create(Set.prototype);
推荐答案
问题?是否有另一种继承模式可以工作?
Is this an implementation issue? Is there another inheritance pattern that will work?
不,这个行为是按照规范正确的。必须在实际集上调用 Set
方法(使用特定于设备的内部插槽进行初始化的对象),并且不是通用的 Array
方法(它基本上适用于具有 .length
属性的所有内容)。
No, this behaviour is correct as by the spec. The Set
methods must be invoked on actual sets (objects initialised with set-specific internal slots), and are not generic as the Array
methods (which basically work on everything that has a .length
property).
As 规范状态:
Set
构造函数被设计为子类化。可以使用
作为类
定义的extends
子句中的值。子类
构造函数,旨在继承指定的集合
行为必须
包含一个超级
调用Set
构造函数创建,
初始化具有
所需内部状态的子类实例支持Set.prototype
内置方法。
The
Set
constructor is designed to be subclassable. It may be used as the value in anextends
clause of aclass
definition. Subclass constructors that intend to inherit the specifiedSet
behaviour must include asuper
call to theSet
constructor to create and initialize the subclass instance with the internal state necessary to support theSet.prototype
built-in methods.
所以你必须使用ES6类语法从内置继承。
So you will have to use ES6 class syntax to inherit from the built-ins.
class MySet extends Set {} // default constructor has super() call
var mySet = new MySet();
mySet.add(1);
是否支持此子类依赖于实现,并不是所有运行时和透明器都符合ES6标准。
Whether this subclassing is supported depends on the implementation, not all runtimes and transpilers are ES6-compliant yet.
这篇关于从Set.prototype继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!