You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Object.create创建对象后无法删除属性,delete返回false求助

为什么delete customObject.price返回false?怎么解决?

嘿,这个问题我之前也踩过坑,核心原因是属性描述符的configurable标志在起作用!

原因分析

当你用Object.create的第二个参数给对象定义属性时,如果你只指定了value字段,其他属性描述符(configurable、enumerable、writable)会默认被设为false。

看你的代码:

var customObject = Object.create(myObject, { price: { value: 100 } } );

这里的price是customObject的自有属性,但它的configurable是false——而delete操作只能删除**configurable为true**的自有属性。所以执行delete customObject.price时操作失败,返回false(如果是严格模式下,还会直接抛出错误)。

解决方法

在定义属性时,显式把configurable设为true即可:

var customObject = Object.create(myObject, { 
  price: { 
    value: 100,
    configurable: true // 开启可配置权限
  } 
} );

这时再执行delete customObject.price就会返回true,属性也会被成功删除。之后访问customObject.price时,就会沿着原型链找到myObject里的price(值为20.99)。

如果需要这个属性同时支持修改、遍历,也可以把对应的描述符一并设为true:

var customObject = Object.create(myObject, { 
  price: { 
    value: 100,
    configurable: true,
    writable: true,
    enumerable: true
  } 
} );

内容的提问来源于stack exchange,提问作者Sai Ram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:43:49