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)
2
Answers
length
is a non-configurable property which is created inside theArray
constructor (see here). So the only way to override it is to use Proxy.Be cautious though – IT CAN DAMAGE THE PERFORMANCE OF YOUR PROGRAM.
You can return an intermediate object with
this
as its prototype withlength
getter/setter.The only problem
super
doesn’t work in this scenario, I guess it’s solvable somehow but I have no clue at the moment.