over 7 years ago

To understand what configurable does, I did a little experiement:

var obj = {};
obj.name = 'cheng';
console.log(obj.name); // cheng


Object.defineProperty(obj, 'name', {configurable: false});
var des = Object.getOwnPropertyDescriptor(obj, 'name');
console.log('Writable: ' + des.writable);          // true

console.log('Configurable: ' + des.configurable);  // false

console.log('Enumerable: ' + des.enumerable);      // true


delete obj.name;       // the delete operation returns false

console.log(obj.name); // prints cheng

Object.defineProperty(obj, 'name', {writable: false});
des = Object.getOwnPropertyDescriptor(obj, 'name');
console.log('Writable: ' + des.writable); // false, so it is ok to change writable to false

Object.defineProperty(obj, 'name', {enumerable: false}); // "TypeError: Cannot redefine property: name, which means enumerable cannot be changed if configurable is set to false

I wonder if I can change those properties to true if they started as false:

var obj = {};

Object.defineProperty(obj, 'name', {configurable: false, writable:false, enumerable: false, value:'cheng'});
var des = Object.getOwnPropertyDescriptor(obj, 'name');
console.log('Writable: ' + des.writable);          // false

console.log('Configurable: ' + des.configurable);  // false

console.log('Enumerable: ' + des.enumerable);      // false


Object.defineProperty(obj, 'name', {configurable: true});   // "TypeError: Cannot redefine property: name

Object.defineProperty(obj, 'name', {writable: true});   // "TypeError: Cannot redefine property: name

Object.defineProperty(obj, 'name', {enumerable: true}); // "TypeError: Cannot redefine property: name

Conclusion

When configurable is set fo false:

  • you cannot delete the property by using the keyword delete
  • you cannot change the property enumerable
  • you CAN change the property writable from true to false but not the other way around
  • you cannot change configurable to true if its current state is false
← JavaScript defineProperty JavaScript for...in vs Object.keys() vs Object.getOwnPropertyNames →
 
comments powered by Disqus