I am interested in setting an accessor on an array's length
using Object.defineProperty()
for academic purposes. This would allow me to notify for size changes dynamically.
While I am familiar with ES6 object observe and watch.js, I prefer exploring this capability in ES5 without relying on additional libraries, even if it is limited to V8/Chrome compatibility.
Consider the following sample array:
var demoArray = ['one', 'two']
In Chrome, the default behavior sets length as non-configurable:
Object.getOwnPropertyDescriptor(demoArray, 'length')
Object {value: 2, writable: true, enumerable: false, configurable: false}
Attempts to set a new property fail:
Object.defineProperty(demoArray, 'length', { set: function(){ console.log('length changed!')} })
This results in a
'TypeError: Cannot redefine property: length'
error message.
Despite the failure, configurable
being false
explains the issue. However, MDN suggests it should be feasible.
How can I successfully use defineProperty
on an array's length
property? Is this achievable?