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 with some kind of downside.
While trying out a few things I came up with this solution for myself:
// This is the constructor of the new class.
function CustomArray() {
// The "use strict" statement changes the way the "magic" variable
// "arguments" works and makes code generally safer.
"use strict";
// Create an actual array. This way the object will treat numeric
// properties in the special way it is supposed to.
var arr = [],
i;
// Overwrite the object's prototype, so that CustomArray.prototype is
// in the prototype chain and the object inherits its methods. This does
// not break the special behaviour of arrays.
Object.setPrototypeOf(arr, CustomArray.prototype);
// Take all arguments and push them to the array.
for (i = 0; i < arguments.length; i++) {
arr.push(arguments[i]);
}
// Return the array with the modified prototype chain. This overwrites
// the return value of the constructor so that CustomArray() really
// returns the modified array and not "this".
return arr;
}
// Make CustomArray inherit from Array.
CustomArray.prototype = Object.create(Array.prototype);
// Define a method for the CustomArray class.
CustomArray.prototype.last = function () {
return this[this.length - 1];
};
var myArray = new CustomArray("A", "B", 3);
// [ "A", "B", 3 ]
myArray.length;
// 3
myArray.push("C");
// [ "A", "B", 3, "C" ]
myArray.length;
// 4
myArray.last();
// "C"
My question is: Is there anything wrong with this code? I find it hard to believe that I came up with "the one solution" after so many people searched before me.