Leila Hamon
Leila Hamon

Reputation: 2595

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

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?

Upvotes: 14

Views: 15576

Answers (3)

Max
Max

Reputation: 2806

Just wanted to add this in

You can change the attributes when first creating an object like so:

var newObj = Object.defineProperty({}, 'aPropertyName', {
    enumerable:false,
    writable:false,
    configurable:false
});

You can also, you can alter multiple properties at once:

var newObj = Object.defineProperties({}, {
    aPropertyName: {enumerable: false, writable: false, configurable: false},
    anotherPropertyName: {enumerable: true, writable: true, configurable: false},
    finalPropertyName: {enumerable: true, writable: false, configurable: true},
});

And of course passing in the object name with the previous method:

Object.defineProperties(objectName, {
    aPropertyName: {enumerable: false, writable: false, configurable: false},
    anotherPropertyName: {enumerable: true, writable: true, configurable: false},
    finalPropertyName: {enumerable: true, writable: false, configurable: true},
});

Upvotes: 2

DadyFuji
DadyFuji

Reputation: 253

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
});

Upvotes: 5

user1106925
user1106925

Reputation:

"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.

Upvotes: 18

Related Questions