Javascript Object.freeze() does not prevent changes to object

后端 未结 3 958
小鲜肉
小鲜肉 2020-12-11 06:01

I am trying to understand the Object.freeze method of ECMAscript.

My understanding was that it essentially stops changes to all the properties of an object. MDN docu

3条回答
  •  甜味超标
    2020-12-11 06:40

    Object.freeze is a shallow freeze.

    If you look at the description in the docs, it says:

    Values cannot be changed for data properties. Accessor properties (getters and setters) work the same (and still give the illusion that you are changing the value). Note that values that are objects can still be modified, unless they are also frozen.

    If you want to deep-freeze an object, here's a good recursive example

    function deepFreeze(o) {
      Object.freeze(o);
    
      Object.getOwnPropertyNames(o).forEach(function(prop) {
        if (o.hasOwnProperty(prop)
        && o[prop] !== null
        && (typeof o[prop] === "object" || typeof o[prop] === "function")
        && !Object.isFrozen(o[prop])) {
            deepFreeze(o[prop]);
          }
      });
    
      return o;
    }
    
    function myObject() {
      this.exampleArray = [];
    }
    
    var obj = deepFreeze(new myObject());
    obj.exampleArray[0] = "foo";
    console.log(obj); // exampleArray is unchanged

提交回复
热议问题