+ 7
The following contains valid Javascript code. I would like to know why the Set s can be constant even if new values are added.
7 ответов
+ 7
In this case const s value is a reference to the memory location of the set. So when you add to the set you are not changing the value stored at const s, instead you are adding/changing the set at the location that const s references/points to. Keep in mind objects are pass by reference and primitives are pass by value.
https://javascript.info/object#copying-by-reference
+ 7
Sonic
I must admit I'm perplexed by the fact that Object freeze() doesn't work on Set nor Map, but it can freeze an array.
Is there a way to freeze an ES6 Map?
https://stackoverflow.com/questions/35747325/is-there-a-way-to-freeze-an-es6-map
+ 5
Sonic
I would look at the source code from Immutable.js to see how they do it.
I've not explored why Object.freeze(set|map) doesn't lock these. I imagine freeze applies to shallow properties and the actual references are probably up the prototype chain. 🤷♂️
+ 4
Thanks ODLNT . So like a const pointer in C I suppose. Is Object.freeze() what is required to make s unmodifiable in the JS code above?
Edit: Object.freeze(s) does not make the code unmodifiable either.
+ 3
ODLNT thanks!
+ 2
Any convenient way to make a Set immutable in JS, David Carroll ?
0
ok