Inherited from Set.prototype

It really bothers 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

The same inheritance pattern does not 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

Is this an implementation issue? Is there any other inheritance pattern that will work? I tried this in node v0.12 and Canary with the same results.

EDIT: This solution works, but I'm still not sure why the same doesn't work above:

var MySet = function(array) {
  var inst = new Set(array);
  inst.__proto__ = MySet.prototype;
  return inst;
}

MySet.prototype = Object.create(Set.prototype);
+4
source share
1 answer

Is this an implementation issue? Is there any other inheritance pattern that will work?

, , . Set (, , ), Array ( , .length).

:

Set . extends class. , Set, super Set , Set.prototype.

, ES6 .

class MySet extends Set {} // default constructor has super() call

var mySet = new MySet();
mySet.add(1);

, , ES6.

+3

Source: https://habr.com/ru/post/1583862/


All Articles