Object.freeze () for TypedArray and ArrayBuffers (node ​​/ chrome) does not work as expected

I have an object with a TypedArray member that I would like to freeze to prevent data from changing after it is installed. Trying to freeze TypedArray or ArrayBuffer did not behave as I expected. I would like to know, just out of curiosity, why he behaves the way he is. I run node 4.4.4 and Chrome, and it behaves 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 tried is to freeze the base 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 so as not to save the original buffer and restore it from data elements when I need it. But I'm just curious about this behavior.

thanks

+5
source share
1 answer

A typed buffer is a reference to the source data, as you have noticed. A typed buffer can refer to a slice of the source buffer, and several typed buffers can refer to the same slice of the source buffer. This is possible, for example, with subarray . Therefore, freezing a typed buffer could not protect the original data from changes. It would be expensive to store all the data about the slices of the original buffer that were frozen and do a check during each change request.

Thus, since the freezing of a typed buffer does not guarantee the preservation of data by the developers of the standard, we decided to ban the freezing of a typed buffer. Another solution that allows the introduction of a typed buffer was frozen with a note that it does not guarantee data storage. An alternative implementation may make a frozen typed buffer view of a read-only interface for data that can be modified by another typed buffer.

The designers of the standard simply chose the easiest way to implement Object.freeze .

-1
source

All Articles