Creating new objects from frozen parent objects

前端 未结 4 1809
栀梦
栀梦 2020-12-05 19:45

This example creates an object, freezes it, and then creates a new object from the frozen object. If the second object tries to change the test property, it can\'t. It remai

4条回答
  •  -上瘾入骨i
    2020-12-05 20:15

    In your case second is a reference to first (like you assumed). A solution would be to clone your object. There is no build in way to clone objects - you have to do it yourself, here is how (source):

    function clone(obj){
       if(obj == null || typeof(obj) != 'object')
          return obj;
    
       var temp = obj.constructor();
    
       for(var key in obj)
           temp[key] = clone(obj[key]);
       return temp;
    }
    

    Then you use it this way:

    var first = {
        test: 10
    };
    Object.freeze(first);
    
    // clone it into a new one
    var second = clone(first);
    second.test = 20;
    console.log(second.test); // 20 where the first is locked
    

提交回复
热议问题