Opposite of Object.freeze or Object.seal in JavaScript

前端 未结 9 1311
无人共我
无人共我 2020-12-02 21:41

What is the opposite of Object.freeze or Object.seal? Is there a function that has a name such as detach?

相关标签:
9条回答
  • 2020-12-02 22:43

    I was issue that problem too. TO fix it, I used JavaScript JSON API to unfreeze my object: const unfreezeObject = JSON.parse(JSON.stringify(freezeObject)). After, I did all mutations I needed.

    0 讨论(0)
  • 2020-12-02 22:45

    You cannot unfreeze (thaw) an object, but if the object is simply a collection of primitives (no functions or classes), you can get a thawed clone of the object like this:

    const unfrozenObj = JSON.parse(JSON.stringify(frozenObj));
    
    0 讨论(0)
  • 2020-12-02 22:46

    Wired solution :)

     Object.unfreeze=function(o){
           var oo=undefined;
            if( o instanceof Array){
                    oo=[];var clone=function(v){oo.push(v)};
                    o.forEach(clone); 
            }else if(o instanceof String){
               oo=new String(o).toString();
          }else  if(typeof o =='object'){
    
             oo={};
            for (var property in o){oo[property] = o[property];}
    
    
            }
            return oo;
     }
    

    Best Practices :


     var obj={a:1,b:2}
     // {a:1,b:2}
       obj.c=3; 
      //{a:1,b:2,c:3}
      Object.freeze(obj)
      //{a:1,b:2,c:3}
      obj.d=5;
      //Error: Read only object 
      obj=Object.unfreeze(obj)
      //{a:1,b:2,c:3}
       obj.d=5;
      //{a:1,b:2,c:3,d:5}
    

     var tab=[1,2,3]
     //[1,2,3]
    tab.push(4)
     //[1,2,3,4]
    Object.freeze(tab);
    //[1,2,3,4]
    tab.push(5)
    // Error : Ready only object
    tab=Object.unfreeze(tab);
    //[1,2,3,4]
    tab.push(9)
    
    //[1,2,3,4,9]
    
    0 讨论(0)
提交回复
热议问题