Record Object.freeze in js

const foo = {
    
    };

// 为 foo 添加一个属性,可以成功
foo.prop = 123;
foo.prop // 123

// 将 foo 指向另一个对象,就会报错
foo = {
    
    }; // TypeError: "foo" is read-only

In the above code, the constant foo stores an address, which points to an object. Only this address is immutable, that is, foo cannot be pointed to another address, but the object itself is mutable, so new attributes can still be added to it.

Below is another example.

const a = [];
a.push('Hello'); // 可执行
a.length = 0;    // 可执行
a = ['Dave'];    // 报错

In the above code, the constant a is an array, and the array itself is writable, but if another array is assigned to a, an error will be reported.

If you really want to freeze the object, you should use the Object.freeze method.

const foo = Object.freeze({
    
    });

// 常规模式时,下面一行不起作用;
// 严格模式时,该行会报错
foo.prop = 123;

In the above code, the constant foo points to a frozen object, so adding new properties does not work, and an error will be reported in strict mode.

In addition to freezing the object itself, the properties of the object should also be frozen. Below is a function that completely freezes an object.

var constantize = (obj) => {
    
    
  Object.freeze(obj);
  Object.keys(obj).forEach( (key, i) => {
    
    
    if ( typeof obj[key] === 'object' ) {
    
    
      constantize( obj[key] );
    }
  });
};

Guess you like

Origin blog.csdn.net/qq_30627241/article/details/131223089