0

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
  • length is an instance property, defining a getter/setter on the prototype won't work Commented Dec 29, 2023 at 12:33
  • You cannot override getter and setter for length. Also, why would you do that? Do you think it's really required? Commented Dec 29, 2023 at 12:52

1 Answer 1

1

length is a non-configurable property which is created inside the Array constructor (see here). So the only way to override it is to use Proxy.

class MyArray extends Array {

    constructor() {
        super()

        return new Proxy(this, {
            get: (target, property, receiver) => {
                if (property === 'length') {
                    console.log('length getter')
                }
                
                return Reflect.get(target, property, receiver)
            },
            set: (target, property, value, receiver) => {
                if (property === 'length') {
                    console.log('length setter')
                }
                
                return Reflect.set(target, property, value, receiver)
            },
        })
        
    }
}

Be cautious though - IT CAN DAMAGE THE PERFORMANCE OF YOUR PROGRAM.

Sign up to request clarification or add additional context in comments.

1 Comment

A good point about the performance. Proxifying arrays slows them down especially with long arrays;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.