So I read some blog posts, SO threads and other lectures about subclassing Array in JavaScript. The general view on the topic is that there is no way to create a subclass wi
Actually array subclassing is possible without even touching Object.setPrototypeOf() or __proto__ by utilizing the mysterious Array.of() method. Array.of() has the ability to switch the constructor function that it uses to construct an array. Since normally it's bound to the Array object it produces normal arrays however once it's bound to another object which can be used as a constructor (a.k.a function) it uses that object as a constructor. Lets make some array sub-classing with Array.of()
function SubArr(){}
SubArr.prototype = Object.create(Array.prototype);
SubArr.prototype.last = function(){return this[this.length-1]};
var what = Array.of.call(SubArr, 1, 2, 3, 4, "this is last");
console.log(JSON.stringify(what,null,2));
console.log(what.last());
console.log(what.map(e => e));
console.log(what instanceof Array);
console.log(Array.isArray(what));
what.unshift("this is first");
console.log(JSON.stringify(what,null,2));
So as you see array sub-classing is pretty simple task when done with Array.of() You can find it's specs here. The interesting part is;
NOTE 2 The of function is an intentionally generic factory method; it does not require that its this value be the Array constructor. Therefore it can be transferred to or inherited by other constructors that may be called with a single numeric argument.