Search code examples
javascriptimmutabilitydefineproperty

{configurable:false} or Object.seal() is not working correctly


I am trying to learn javascript, and have seen that we can play with object's property's attributes. (i mean value, writable, enumerable, configurable).

And from what i learned, i have thought changing {configurable: false} would restrict any more configuration changes like {writable: false, enumerable: false}

I have written below to try it out, but the results i have got were nothing like the results i have expected.

Am i wrong about what {configurable:false} means or, is there something wrong with the code? TIA.

"use strict";

window.onload = function(){

  var o = {x:1};

  //Make "x" non-configurable
  Object.defineProperty(o, "x", {configurable: false});
  //Seal "o";
  Object.seal(o);

  console.log(Object.getOwnPropertyDescriptor(o, "x"));
  //outputs => Object { value: 1, writable: true, enumerable: true, configurable: false }
  console.log(Object.isSealed(o));
  //outputs => true

  Object.defineProperty(o, "x", {writable: false}); //this doesn't cause any errors.
  console.log(Object.getOwnPropertyDescriptor(o, "x"));
  //outputs => Object { value: 1, writable: false, enumerable: true, configurable: false }
}


Solution

  • MDN - seal

    Configurable attribute
    The configurable attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than writable to false) can be changed

    The Object.seal()
    method seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed as long as they are writable.

    You need freeze

    MDN - freeze

    Comparison to Object.seal() Objects sealed with Object.seal() can have their existing properties changed. Existing properties in objects frozen with Object.freeze() are made immutable.

    "use strict";
    
    window.onload = function(){
    
      var o = {x:1};
    
      //Make "x" non-configurable
      Object.defineProperty(o, "x", {configurable: false});
      //freeze "o";
      Object.freeze(o);
    
      console.log(Object.getOwnPropertyDescriptor(o, "x"));
      //outputs => Object { value: 1, writable: true, enumerable: true, configurable: false }
      console.log(Object.isSealed(o));
      //outputs => true
    
      Object.defineProperty(o, "x", {writable: true}); //Now this doesn't cause.
      console.log(Object.getOwnPropertyDescriptor(o, "x"));
      //outputs => Object { value: 1, writable: false, enumerable: true, configurable: false }
    }