I am trying to subclass JavaScript array and override 'length' getter and setter. This code is not working - it outputs nothing to the console because getter and setter are not called. How to fix this?
class MyArray extends Array {
get length() {
console.log('length getter')
return super.length
}
set length(value) {
console.log('length setter')
super.length = value
}
}
const arr = new MyArray()
arr.length = 1
console.log(arr.length)
lengthis a non-configurable property which is created inside theArrayconstructor (see here). So the only way to override it is to use Proxy.Be cautious though - IT CAN DAMAGE THE PERFORMANCE OF YOUR PROGRAM.