while Set
is an Object, Object.freeze()
works on the object's properties, which evidently Map and Set do not use: eg
let m = new Map(); Object.freeze(m); m.set( 'key', 55); m.get( 'key' ) ==> 55
this is the behavior in Chrome, and I expect it's standard.
I understand that one could (sometimes) transform the Set or Map into a normal Object, and then freeze the object. but then key access changes between the unfrozen and frozen version.
As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. freeze() returns the same object that was passed into the function.
Object.freeze() Method freeze() which is used to freeze an object. Freezing an object does not allow new properties to be added to an object and prevents from removing or altering the existing properties. Object. freeze() preserves the enumerability, configurability, writability and the prototype of the object.
Object. freeze() is shallow. It will make the object immutable, but the nested properties and methods inside said object can still be mutated.
Interesting question, but doesn't currently seem like a directly supported feature on a Set
or Map
object.
Here are some work-arounds I can think of using the Set
object as a guide:
You could create a proxy object that removed .add()
, .clear()
and .delete()
, but allowed proxied access to all other methods that just read data. This would hide access to the actual Set
object so there would be no way to access it directly and provide proxied access to all other methods.
You could override .add()
, .clear()
and .delete()
on a given Set
instance with methods that did nothing or threw an exception which would prevent modification. If you made those override methods non-configurable and then did a .freeze()
on the object, those methods couldn't be put back. One could use Set.prototype.add
directly on the Set
object to still bypass it though.
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