开发者

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

开发者 https://www.devze.com 2023-03-24 16:47 出处:网络
I\'m trying to define an object and create an accessor property for it. HTML: <input type=\'hidden\' id=\'crudMode\' value=\'Create\' />

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){ 
    开发者_Go百科    $('#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?


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


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

    const crudModeCopy = {...crudMode}

and now it is configurable

0

精彩评论

暂无评论...
验证码 换一张
取 消