javascript - 如何解决 Object.defineProperty 的可配置问题?

标签 javascript

根据我的理解,如果可配置设置为 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/

相关文章:

javascript - 获取并检查数组的 javascript 数组

c# - 如何检查 cookie 是否存在,即使它是在另一个应用程序中创建的? (使用 JS 或 C#)

javascript - 是否仅使用 mongodb 1.4 及更早版本运行 mongoskin?

javascript - 以有效的 .Net 格式在 javascript 中对日期进行字符串化

javascript - 从我的 React 组件中的第三方组件实例调用操作

javascript - 我可以向另一个域发出 XMLHttpRequest 吗?

javascript - 有没有更好的方法将多值数据显示为列?

javascript - 为不同的浏览器窗口大小选择不同的CSS样式表?

javascript - typescript & TypeORM : Cannot use import statement outside a module

javascript - 自定义编码字符串