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

后端 未结 3 953
小鲜肉
小鲜肉 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:38

    Set the property descriptors for the object to writable:false, configurable:false using Object.defineProprties; then call Object.preventExtensions on the object. See How to create static array in javascript.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-11 06:43

    It's pretty weird, but freezing prevents an element of mutating, adding elements to an array is not mutating (weirdly enough)...

    For example in ES6 when you define a variable that won't change you declare it with "const" and not "let". If you say:

    const foo = 'foo'; const foo = 'bar;

    it will throw an error because you used const. When you say

    const foo = ['foo']; foo.append('bar');

    it won't throw an error.

    0 讨论(0)
提交回复
热议问题