javascript - 如何使不可扩展的对象可扩展?
问题描述
我需要更改一个不可扩展的对象。有什么办法可以改变这个对象属性吗?
我已阅读文档说“一旦对象不可扩展,就无法再次使其可扩展。”
有什么解决方法吗?比如复制对象什么的?
解决方案
除了复制对象之外,另一种可能性是创建一个其原型为不可扩展对象的新对象:
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);
推荐阅读
- mysql - 如何将 MySQL 数据库从 AMPPS 转移到 XAMPP vm Stack
- javascript - 未捕获的类型错误:无法读取属性“值”
- colors - 在 Shopify 产品页面上显示一种颜色选项
- javascript - 需要检查登录用户名和密码,然后从以前的条目中获取数据
- arrays - 在 TypeScript 中用另一个嵌套数组对象从一个数组中查找并替换带有 id 的值
- c# - 获取匹配表达式的字典值计数的最佳方法是什么?
- c# - ASP.NET Core 5.0 OData $select 不工作
- jquery - jquery 验证复选框
- matlab - 多标签组合数据集 MATLAB 的训练、验证和测试中的混洗和分区
- python - 在 Flask 中使用块时遇到问题