I'm having an object with a TypedArray member that I'd like to freeze to prevent modifying the data once it's set. Attempting to freeze a TypedArray or it's ArrayBuffer did not behaved as I've expected. I'd like to know, simply out of curiosity, why it behaves the way it is. I'm running node 4.4.4 and Chrome and it behaves the same more or less.
var typedArray = new Uint32Array(4);
typedArray[0] = 10;
typedArray[1] = 20;
Object.freeze(typedArray);
// throws TypeError : Cannot freeze array buffer views with elements(...)
The next thing I've tried is to freeze the underlying ArrayBuffer
Object.freeze(typedArray.buffer); // Does not throws errors
Object.isFrozen(typedArray.buffer); // returns true
typedArray[0] = 50; // Successfully modifies the data, despite the buffer is frozen
I know that I can change my design to not keep the original buffer, and reconstruct it from data members once I need it. But I'm just curious about this behavior.
Thanks
Typed buffer is kind of reference on original data as you noticed. Typed buffer could refer a slice of the original buffer, and several typed buffers could refer the same slice of the original buffer. It's possible, for example with subarray. That's why freezing typed buffer could not protect original data from been changed. It would be to expensive to store all the data about slices of the original buffer which were frozen and make a check during each change query.
So, because freezing typed buffer does not guarantee data preserving designers of the standard decided to forbid freezing of typed buffer. Another solution to let typed buffer been frozen with a note that it does not guarantee data preservation. Alternative implementation could make frozen typed buffer kind of read-only interface to data which could be changed by another typed buffer.
Designers of the standard simply chosen the simplest way of implementing Object.freeze routine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With