when do you use Object.defineProperty()

前端 未结 10 2370
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 01:31

I\'m wondering when I should use

Object.defineProperty

to create new properties for an object. I\'m aware that I\'m able to set things lik

10条回答
  •  我在风中等你
    2020-12-08 02:24

    Summary:

    In Javascript Objects are collections of key-value pairs. Object.defineProperty() is a function which can define a new property on an object and can set the following attributes of a property:

    • value : The value associated with the key
    • writable : if writable is set to true The property can be updated by assigning a new value to it. If set to false you can't change the value.
    • enumerable : if enumerable is set to true Property can be accessed via a for..in loop. Furthermore are the only the enumerable property keys returned with Object.keys()
    • configurable : If configurable is set to false you cannot change change the property attributes (value/writable/enumerable/configurable), also since you cannot change the value you cannot delete it using the delete operator.

    Example:

    let obj = {};
    
    
    Object.defineProperty(obj, 'prop1', {
          value: 1,
          writable: false,
          enumerable: false,
          configurable: false
    });   // create a new property (key=prop1, value=1)
    
    
    Object.defineProperty(obj, 'prop2', {
          value: 2,
          writable: true,
          enumerable: true,
          configurable: true
    });  // create a new property (key=prop2, value=2)
    
    
    console.log(obj.prop1, obj.prop2); // both props exists
    
    for(const props in obj) {
      console.log(props);
      // only logs prop2 because writable is true in prop2 and false in prop1
    }
    
    
    obj.prop1 = 100;
    obj.prop2 = 100;
    console.log(obj.prop1, obj.prop2);
    // only prop2 is changed because prop2 is writable, prop1 is not
    
    
    delete obj.prop1;
    delete obj.prop2;
    
    console.log(obj.prop1, obj.prop2);
    // only prop2 is deleted because prop2 is configurable and prop1 is not

提交回复
热议问题