Seal, Freeze, PreventExtension ( ) Methods - Object Extensibility

Video

JavaScript Notes

JavaScript
    /**
    * Exploring the differences among
    * Object.seal() - check with Object.isSealed()
    * Object.freeze() - check with Object.isFrozen()
    * Object.preventExtensions() - check with Object.isExtensible()
    */

    "use strict"; // make sure error messages appear. Prevent Silent Failures
    
    //create an object to use as the prototype
    let parentObj = {
        prop1: 123,
        someMethod: function(){
            console.log("hello");
        }
    }

    //create an object and assign the prototype
    let obj = Object.create(parentObj, {
        prop2: {
            writable: true,
            configurable: true,
            enumerable: true,
            value: "I am prop2"
        }
    });

    obj.innerMethod = function(){
        console.log("obj inner method");
    }    // add a method on the object directly

    // add a property to the object and define its property descriptors
    Object.defineProperty(obj, "prop3", {
            value: true,
            configurable: true,
            writable: true,
            enumerable: true,
        }
    });

    // create another object to use as an alternative prototype
    let otherProto = {};

    Object.seal(obj);
    Object.freeze(obj);
    Object.preventExtensions(obj);
    Object.setPrototypeOf(obj, otherProto);    // will fail on any of the seal, freeze, etc. methods

    /**
    *After calling the method you can..
    *                        seal()        freeze()        preventExtensions()
    * Add new prop            no            no                    no
    * Edit prop value        yes            no                    yes
    * Delete a prop           no            no                    yes
    * Change descriptors      no            no                    yes
    * Reassign __proto__      no            no                    no
    *
    * __proto__ is the old non-standard property equivalent of Object.getPrototypeOf(obj)
    */