Opposite of Object.freeze or Object.seal in JavaScript

前端 未结 9 1358
无人共我
无人共我 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:32

    You can't unfreeze a frozen object.

    You can however make it so pesky libraries can't freeze anything in the future, by overriding the Object.freeze method to be a no-op:

    Object.freeze = function(obj) { return obj; }; // just return the original object
    

    In most cases this is enough. Just run the code above before the library is loaded, and it can no longer freeze anything. ; )


    EDIT: Some libraries, such as immer@7.0.7, have issues unless Object.isFrozen(obj) returns true after Object.freeze(obj) is called.

    The below is thus a safer way of blocking object-freezing: (the primitive checks are because WeakSet errors if you pass in primitives)

    const fakeFrozenObjects = new WeakSet();
    function isPrimitive(val) {
        return val == null || (typeof val != "object" && typeof val != "function");
    }
    Object.freeze = obj=>{
        if (!isPrimitive(obj)) fakeFrozenObjects.add(obj);
        return obj;
    };
    Object.isFrozen = obj=>{
        if (isPrimitive(obj)) return true;
        return fakeFrozenObjects.has(obj);
    };
    

提交回复
热议问题