Provide immutability or partial immutability, which is not subject to silence

Is there a way to enforce partial immutability of an object that throws an error if someone tries to change it?

For example, let obj = {a: 1, b: 2}and I want to obj.aand obj.bhave the same, but that still lets you add additional keys to obj, that is, to resolve obj.c = 3.

I thought about nesting properties in sub-objects and used Object.freezeas follows:

let obj = {subObj:{a: 1, b:2}}; 
Object.freeze(obj.subObj);

But it seems that after that he fails, i.e. obj.subObj.a = 3does not mutate a, but also does not give any indication of a problem. Is there any way to make it throw an error?

+4
source share
3 answers

An easy way to do this would be with getters that return static values ​​and that throw errors.

let obj = {
  get a() {
    return 1;
  },
  set a(val) {
    throw new Error('Can\'t set a');
  },
  get b() {
    return 2;
  },
  set b(val) {
    throw new Error('Can\'t set b');
  }
};
obj.c = 3; // works
console.log(obj);
obj.a = 4; // throws an error
Run codeHide result
+3
source

You can use Object.defineProperties()a writablefor falsefor properties "a"and "b", "use strict",try..catch..finally

"use strict";

let obj = new Object;

Object.defineProperties(obj, {
  "a": {value:1, writable: false},
  "b": {value:2, writable: false}
});

try {
  obj.c = 3;
  obj.a = 3;
} catch (e) {
    console.log(e);
} finally {
    console.log(obj);
}
Run codeHide result
+3
source

You can try using strict mode .

Add the following beginning of the file:

'use strict'

It will throw an exception if u will modify your object after freezing.

+2
source

Source: https://habr.com/ru/post/1677100/


All Articles