我需要更改不可扩展的对象。有什么办法可以改变这个对象属性吗?
我已经阅读了文档,它说“一旦对象不可扩展,就无法再次使对象可扩展。”
有什么解决方法吗?比如复制对象什么的?
除了复制对象之外,另一种可能性是创建一个新对象,其原型是不可扩展对象:
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);Run Code Online (Sandbox Code Playgroud)