I would like (mainly for academic reasons) to be able to set an accessor on an array's length
using Object.defineProperty()
, so than I can notify for size changes.
I am aware of ES6 object observe, and watch.js, but I would like to attempt to do this in ES5 without extra libraries if possible, even if this is only for V8/Chrome.
A sample array:
var demoArray = ['one', 'two']
Alas Chrome, out of the box, makes length not configurable:
Object.getOwnPropertyDescriptor(demoArray, 'length')
Object {value: 2, writable: true, enumerable: false, configurable: false}
And it doesn't work:
Object.defineProperty(demoArray, 'length', { set: function(){ console.log('length changed!')} })
Fails with 'TypeError: Cannot redefine property: length'
As you can see, configurable
is false
- so the failure is understandable. However according to MDN it should be possible.
How can I get defineProperty
working on an array's length
property? Should this work?
writable
property descriptor (and maybe thevalue
one), but changing the data property to an accessor property is definitely prohibited. – Angiomavalue
usingdefineProperty
, which should be possible according to the spec, but is some implementations is sometimes blocked erroneously (as if it incorrectly hadwritable: false
). However, defining a setter is right out, in compliance with the spec. – SerafinaObject.defineProperty(demoArray, 'length', {value: 0});
but setting an accessor property won't work and breaks the spec. – Chronicleslength
being redefinable doesn't mean you get a pass on all the other restrictionsObject.defineProperty
ordinarily enforces. Specifically: until you changelength
's writability to false, you can only changelength
's writability and value. You can't change the property to a getter/setter pair, ever. – Bartlett