There’s almost no point extending the built-in Array unless you have some very specific use-case (or just for experimentation). It’s not going to give you something particularly useful because it’s just going to be a pain to make use of it. So
class MyArray extends Array {}
There we go, a subclassed Array. However, you can’t now use []
to create your arrays, you need to do:
const myArr = new MyArray(1, 2, 3, 4, 5);
So maybe you add a function to sorta do that:
class MyArray extends Array {
static fromArray(arr) {
return new MyArray(...arr);
}
}
I mean, it actually needs the constructor adjusting because if you pass fromArray
an array with one element, and that element is a number n
, then it’ll create you a new MyArray
with n
empty slots, but anyway…
Also these don’t work, you don’t get static methods inherited, you would need to reimplement them (basically what I did above)
MyArray.from([1,2,3])
MyArray.of(1, 2, 3)
MyArray.isArray([1, 2, 3])
Much easier to just polyfill:
if (!Array.prototype.destructiveFart) {
Array.prototype.destructiveFart = function () {
for (let i = 0; i < this.length; i++) {
this[i] = "fart";
}
};
}
edit: here’s the Proxy from before as well:
function secretStuff(obj) {
let handler = {
get(target, propKey, receiver) {
if (propKey in Array.prototype) {
const defaultArr = target.default;
return function(...args) {
let result = target.default[propKey](...args);
console.log(`
I think you're trying to run an array method!
Running ${propKey.toUpperCase()} method on the default array ${JSON.stringify(target.default)}
Result: ${JSON.stringify(result)}
`);
return result;
};
} else {
console.log(`
I don't think this is an array method!
You're probably trying to access some normal property!
Result: ${JSON.stringify(target[propKey])}
`);
return target[propKey];
}
}
};
return new Proxy(obj, handler);
}