本文介绍了使现有的不可写和不可配置的属性可写和可配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个对象:

var agent = new Agent({name: 'James', type: 'secret', id: 007})

构建Agent类时,我决定使id属性不可变:

When I built the Agent class, I decided to make the id property immutable:

Object.defineProperty(Agent.prototype, 'id', {
    configurable: false,
    writable: false
})

但是在某些时候,我想将对象标记为删除.而且由于我们实际上无法删除 this ,因此我将通过删除 id 属性来削弱对象.因此,我再次使该属性可写:

But at some point I will want to mark the object for deletion. And because we can't actually delete this, I'm going to cripple the object by removing the id property instead. So I go to make the property writable again:

Object.defineProperty(agent, 'id', {
    configurable: true,
    writable: true
})
delete agent.id

但是我当然知道:

TypeError: Cannot redefine property: id

因为 id 已经存在.

如何使现有不可写属性可写?

How can I make an existing non-writable property writable?

推荐答案

Mozilla文档

换句话说,如果要稍后修改属性定义(以使其可写),则必须在第一个属性定义中将 configurable 设置为 true .

In other words, you must set configurable to true in the first property definition if you want to modify the property definition (to be writable) later.

请注意,当 configurable false 时,您可以采用另一种方法(将可写属性设置为不可写),但这与您在此处所做的相反

Note that you can go the other way (make writable property non-writable) when configurable is false, but that is the opposite of what you're doing here.

这篇关于使现有的不可写和不可配置的属性可写和可配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 10:36