I thought it would be useful to extend Arrays in javascript, to enhance them with some custom methods and business logic. It worked fine so far until I tried to filter on my instances.
It seems like the array filter
method calls my constructor with one argument (0
if nothing is found) and returns a new instance. Not what I expected.
class MyArray extends Array {
constructor(x, y, z) {
super(x, y, z);
// do custom stuff
}
}
let numbers = new MyArray(1, 2, 3);
console.log(numbers.filter((v) => v === 0));
Though, if I pass and spread some arguments into a single variable, everything works.
Technically I see no difference between the two, I don't get it!
class MyArray extends Array {
constructor(x, ...args) {
super(x, ...args);;
// do custom stuff
}
}
let numbers = new MyArray(1, 2, 3);
console.log(numbers.filter((v) => v === 0));
- Why does the first approach run into this issue?
- Why does the second approach not run into this?
(Is it bad practice to extend Arrays or other core js classes?)