简体   繁体   中英

Remove property descriptors in Javascript

Is there a way to remove property descriptors set with Object.defineProperty ? The configurable descriptor can be true . Deleting the property and adding it back is one way to do it, but is there a built-in way?

It is not possible to modify a property's descriptor if its configurable flag is set to false. As MDN states :

A TypeError is thrown when attempts are made to change non-configurable property attributes (besides the writable attribute) unless the current and new values are the same.

So, your hacky approach is the only way to achieve this.

That being said, properties are set to non-configurable for a reason and if your application relies on making non-configurable properties configurable, then perhaps there is a code smell in your application.

Object.defineProperty does not, technically speaking, "set property descriptors"; it sets flags, value, and getter/setter based on a property descriptor. Therefore, it makes no sense to say "remove a property descriptor"; it only makes sense to say "remove a property", or "redefine a property".

The way to remove a property itself is with delete . If you then want to add it back, then you add it back.

The way to redefine a property is to redefine it. There is no way to selectively modify some of the flags of the property. Object.defineProperty is all-or-nothing. So if you want to change something like writeable , then yes, you have to call Object.defineProperty again with the entire set of new keys. This is analogous to the problem of how to add a set to a property after it is already defined with a get . There is no way to just add the set . You have to redefine the property with a get and a set .

You can call Object.getOwnPropertyDescriptor to get a descriptor embodying the current flags etc., then modify that and call Object.defineProperty with it. This will completely replace the previous property (assuming it was configurable). This is not a hack; it's just the way that you would reset the flags of a property. By the way, there is no particular need to delete .

However, once you have established a property with the configurable flag set to false, you are pretty much out of luck. Not only can you not redefine that property, you cannot even delete it in order to define it anew.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM