gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 18:39:30 25 4
gpt4 key购买 nike

在我的理解中,如果 configurable 设置为 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 时,即使 configurable 为 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键,描述符类型默认为数据描述符,如果没有传递value,其值为undefined

您最后看到的错误是不同的。虽然您可以将可写、不可配置的数据描述符更改为不可写的数据描述符,但您不能反过来——不可写、不可配置的数据描述符不能转换为可写的数据描述符。 (参见 ValidateAndApplyPropertyDescriptor 的第 7 步)

关于javascript - 如何解决 Object.defineProperty 的可配置问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58249804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com