Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make existing non-writable and non-configurable property writable and configurable

Tags:

javascript

Say I've got an object:

var agent = new Agent({name: 'James', type: 'secret', id: 007})

When I built the Agent class, I decided to make the id property immutable:

Object.defineProperty(Agent.prototype, 'id', {
    configurable: false,
    writable: false
})

But at some point I will want to mark the object for deletion. And because we can't actually delete this, I'm going to cripple the object by removing the id property instead. So I go to make the property writable again:

Object.defineProperty(agent, 'id', {
    configurable: true,
    writable: true
})
delete agent.id

But of course I get:

TypeError: Cannot redefine property: id 

Because id already exists.

How can I make an existing non-writable property writable?

like image 435
brandonscript Avatar asked Jan 06 '16 21:01

brandonscript


1 Answers

The Mozilla documentation says

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false (the property is said to be “non-configurable”), then no attribute besides writable can be changed. If a property is non-configurable, its writable attribute can only be changed to false.

In other words, you must set configurable to true in the first property definition if you want to modify the property definition (to be writable) later.

Note that you can go the other way (make writable property non-writable) when configurable is false, but that is the opposite of what you're doing here.

like image 150
Dark Falcon Avatar answered Oct 27 '22 04:10

Dark Falcon