首页 > 解决方案 > 如何使不可扩展的对象可扩展?

问题描述

我需要更改一个不可扩展的对象。有什么办法可以改变这个对象属性吗?

我已阅读文档说“一旦对象不可扩展,就无法再次使其可扩展。”

有什么解决方法吗?比如复制对象什么的?

标签: javascriptobject

解决方案


除了复制对象之外,另一种可能性是创建一个其原型为不可扩展对象的新对象:

const object1 = {
  foo: 'foo',
};
Object.preventExtensions(object1);
// We can't assign new properties to object1 ever again, but:

const object2 = Object.create(object1);
object2.bar = 'bar';
console.log(object2);

/* This will create a property *directly on* object2, so that
  `object2.foo` refers to the property on object2,
  rather than falling back to the prototype's "foo" property: */
object2.foo = 'foo 2';
console.log(object2);


推荐阅读