gpt4 book ai didi

javascript - 如何使不可扩展的对象成为可扩展的?

转载 作者:行者123 更新时间:2023-11-30 09:20:54 26 4
gpt4 key购买 nike

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

我已经阅读了这样说的文档“一旦对象不可扩展,就无法再使它可扩展。”

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

最佳答案

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

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);

关于javascript - 如何使不可扩展的对象成为可扩展的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51760123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com