根据我的理解,如果可配置设置为 false,则属性描述符无法更改(不允许重新定义)。
但是当我在 chrome、node、firefox、safari 中测试时,我得到了相同的结果:
o = {}
Object.defineProperty(o, 't', {writable: true, configurable: false})
Object.defineProperty(o, 't', {writable: false, configurable: false}) // descriptor changes without error
Object.defineProperty(o, 't', {writable: true, configurable: false})
// this time I got expected error - TypeError: Attempting to change writable attribute of unconfigurable property.
看起来当 writable 为 true 时,即使可配置为 false,我们仍然可以更改属性描述符。
或者,始终允许将描述符更改为 false?
什么是正确的行为?
最佳答案
configurable
的用途 is :
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
看看:
Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.
属性描述符的类型是指该描述符是数据描述符(值有意义的描述符)还是访问器描述符(具有 getter/setter)。不可配置的属性无法从数据类型更改为 getter/setter 类型,反之亦然。
const o = {};
Object.defineProperty(o, 't', {writable: true, configurable: false})
console.log(Object.getOwnPropertyDescriptor(o, 't'));
Object.defineProperty(o, 't', { get() { }})
如果传递writable
键,则描述符类型默认为数据描述符,如果没有传递值
,则其值为undefined
。
您最后看到的错误是不同的。虽然您可以将可写的不可配置的数据描述符更改为不可写的数据描述符,但您不能采取相反的方式 - 不可写的不可配置的数据描述符无法转换为可写的数据描述符。 (参见ValidateAndApplyPropertyDescriptor的第7步)
关于javascript - 如何解决 Object.defineProperty 的可配置问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58249804/