In JavaScript, is it possible to change the constructor of an object initializer?

时间:2018-04-18 18:03:12

标签: javascript constructor immutability

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?

1 个答案:

答案 0 :(得分: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