javascript 访问器属性错误:无法重新定义不可配置的属性“状态”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6924250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error in accessor property: can't redefine non-configurable property 'status'
提问by Saeed Neamati
I'm trying to define an object and create an accessor propertyfor it.
我正在尝试定义一个对象并为其创建一个访问器属性。
HTML:
HTML:
<input type='hidden' id='crudMode' value='Create' />
JavaScript:
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?
这里有什么问题?
回答by Matthew Wilson
MDC documentation says that, as well as 'get' and 'set', you need a flag 'configurable' set to true when calling Object.defineProperty.
MDC 文档说,除了 'get' 和 'set',在调用 Object.defineProperty 时,您还需要将标志 'configurable' 设置为 true。
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty