14

I'm trying to define an object and create an accessor property for it.

HTML:

<input type='hidden' id='crudMode' value='Create' />

JavaScript:

crudMode = {
   create: "Create",
   read: "Read",
   update: "Update",
   delete: "Delete",
   current: function () { return $('#crudMode').val(); }
}

Object.defineProperty(crudMode, 'mode', {
    get: function(){
        return this.current();
    },
    set: function(value){ 
        $('#crudMode').val(value);
    }
});

But when I use it, it throws the mentioned error in the question title:

console.log(crudMode.mode);

Throws:

TypeError: can't redefine non-configurable property 'mode'

What's wrong here?

pimvdb
  • 151,816
  • 78
  • 307
  • 352
Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188
  • Does this answer your question? [Why can't I redefine a property in a Javascript object?](https://stackoverflow.com/questions/25517989/why-cant-i-redefine-a-property-in-a-javascript-object) – Michael Freidgeim Oct 22 '20 at 22:14

2 Answers2

19

MDC documentation says that, as well as 'get' and 'set', you need a flag 'configurable' set to true when calling Object.defineProperty.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty

Matthew Wilson
  • 3,861
  • 21
  • 14
  • 3
    Can I override property that has once been set unconfigurable? – Tomáš Zato Nov 20 '14 at 08:57
  • 5
    @TomášZato the answer to your question is in the primary documentation linked to above. Once a property has been defined with `configurable` set to `false`, the property can not be modified or deleted. – Mark Stosberg Nov 26 '14 at 16:58
0

You Can simply create a clone of the object, if it is not configurable,

    const crudModeCopy = {...crudMode}

and now it is configurable