Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change writable enumerable and configurable values of a Javascript object property?

Tags:

javascript

From the node repl:

foo = { bar: 'baz'};
console.log (Object.getOwnPropertyDescriptor(foo, 'bar'))

Returned value:

{ value: 'baz',
  writable: true,
  enumerable: true,
  configurable: true }

How do you change the writable enumerable, and configurable to false? What are these values called? Are they part of ES5.1? Are there more that the repl didn't output?

like image 497
Leila Hamon Avatar asked Jul 01 '12 02:07

Leila Hamon


People also ask

How do you change the property of an object JavaScript?

Setting Properties of Existing Objects After you have created an object, you can set or change its properties by calling the property directly with the dot operator (if the object inherits from IDL_Object) or by calling the object's SetProperty method.

What is configurable property in JavaScript?

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

Which of the are special attributes of a property writable enumerable configurable all the above?

writable – if true , the value can be changed, otherwise it's read-only. enumerable – if true , then listed in loops, otherwise not listed. configurable – if true , the property can be deleted and these attributes can be modified, otherwise not.


2 Answers

"How do you change the writable enumerable, and configurable to false?"

Object.defineProperty(foo, 'baz', {
    enumerable:false,
    writable:false,
    configurable:false
});

There's also Object.defineProperties, which is the same, except you can set multiple properties, and Object.create, which let's you create a new object, and set its prototype object, and its descriptors.

"What are these values called?"

They're property descriptors.

"Are they part of ES5.1?"

Yes, ES5.

"Are there more that the repl didn't output?"

More what, property descriptors? No.

like image 100
user1106925 Avatar answered Oct 18 '22 14:10

user1106925


squint:I think there is like a little typing error in your answer.

Your code:

Object.defineProperty(foo, 'baz', {
enumerable:false,
writable:false,
configurable:false
});

but the second argument must be the name of the property and not the value, so the correct code is:

Object.defineProperty(foo, 'bar', {
enumerable:false,
writable:false,
configurable:false
});
like image 37
DadyFuji Avatar answered Oct 18 '22 14:10

DadyFuji