Error in accessor property: can't redefine non-configurable property 'status'
Asked Answered
D

2

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?

Downing answered 3/8, 2011 at 9:23 Comment(1)
Does this answer your question? Why can't I redefine a property in a Javascript object?Vaccaro
D
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

Damsel answered 3/8, 2011 at 12:9 Comment(2)
Can I override property that has once been set unconfigurable?Belting
@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.Ssm
M
0

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

    const crudModeCopy = {...crudMode}

and now it is configurable

Maiolica answered 30/6, 2022 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.