0

In JavaScript, I would like to create persistent immutable collections from object initializers, such as arrays and maps, to make such collections more readable. It is possible to use get functions:

Object.defineProperty(Object.prototype, 'i', { get: function() {
  ...code to convert map to immutable map...
} });

let b = {name:"John Doe", age: 34}.i;

But is it possible to change the construct methods, used by the object initializers for Object and Array, to make them create immutable versions?

dilvan
  • 2,109
  • 2
  • 20
  • 32

1 Answers1

2

Extending Object is really bad practice. What you want to accomplish is done by https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze in modern JS. For other cases the answer is no, the last constructor must be known when calling new, and you would also want to replace all methods that edit in-place such as splice or sort for arrays, I'd avoid doing so if possible. Actually that's not completely accurate, see conversation here Overwriting the Array constructor does not affect [], right? - but really, just don't

Eric
  • 1,689
  • 15
  • 12
  • I want to return persistent immutable collections (I updated the question), so freeze isn't an option. Amazing the fact that it is still possible to replace Array (but not Object). – dilvan Apr 18 '18 at 18:32
  • There are excellent reasons for that in both ES engine implementation, and in that what you're looking for is really breaking all hope of compartmentalisation for code to cooperate with yours. If you must make a read-only array, just make your own class to that effect with only a `get: function(index)` method exposed and use that where you need it. Hoping you'll never need to work with code that makes other assumptions about Array will prove hurtful in the long term. – Eric Apr 18 '18 at 19:06