Difference between Configurable and Writable attributes of an Object

后端 未结 4 1941
情歌与酒
情歌与酒 2020-12-29 23:27

I saw the following regarding javascript, object data property attributes

— 
Configurable: Specifies whether the property can be deleted or changed.

— Enume

相关标签:
4条回答
  • 2020-12-30 00:07

    From: http://ejohn.org/blog/ecmascript-5-objects-and-properties/

    Writable: If false, the value of the property can not be changed.

    Configurable: If false, any attempts to delete the property or change its attributes (Writable, Configurable, or Enumerable) will fail.

    Enumerable: If true, the property will be iterated over when a user does for (var prop in obj){} (or similar).

    0 讨论(0)
  • 2020-12-30 00:07

    configurable and writable are NOT representing the same thing.

    configurable means property descriptor and existence.

    writable means property value only.

    A property's descriptor contains value, enumerable, configurable and writable.

    scenario 1: create property by assignment

    'use strict';  // non-strict mode behaves slightly different
    
    var foo = {};
    foo.bar = 1;  // operated by CreateDataProperty*
    
    // the above is the same as
    Object.defineProperty(foo, 'bar', {
      value: 1,
      configurable: true,
      writable: true,
      // ...
    });
    
    • CreateDataProperty is an operation defined together with ECMAScript spec.

    scenario 2: create property by descriptor

    'use strict';  // non-strict mode behaves slightly different
    
    var foo = {};
    Object.defineProperty(foo, 'bar', {
      value: 1,
      // configurable => false
      // writable => false
    });
    
    foo.bar = 2;    // throw TypeError: Cannot assign to read only property
    
    Object.defineProperty(foo, 'bar', {
      value: 2
      // ...
    }); // throw TypeError: Cannot redefine property
    
    delete foo.bar; // throw TypeError: Cannot delete property
    
    0 讨论(0)
  • 2020-12-30 00:20

    Configurable prevents any attempts to 'redefine' properties of a key with Object.defineProperty, chrome will throw an error sign

    Uncaught TypeError: Cannot redefine property: foo

    The writable attribute simply avoids this value from being edited

    0 讨论(0)
  • 2020-12-30 00:23

    If Writable is set to true means the object property's value can be changed.

    If Configurable is set to true, means the object property's type can be changed from data property to accessor property (or vice versa); and the object property can be deleted.

    0 讨论(0)
提交回复
热议问题