javascript - 为什么将对象设置为不可扩展使其 [[prototype]] 不可变?
问题描述
MDN - Object.preventExtensions页面说
此方法使
[[prototype]]
目标的 不可变;任何[[prototype]]
重新分配都会抛出一个TypeError
. 此行为特定于内部[[prototype]]
属性,目标对象的其他属性将保持可变。
我的问题是:
为什么将对象设置为不可扩展使其 [[prototype]] 不可变?( Object.preventExtensions()
,Object.seal()
等Object.freeze()
)
解决方案
如果 internal[[prototype]]
不是不可变属性,您可以通过使用 将对象的内部与另一个值Object.preventExtensions()
交换来规避,有效地将新值的所有属性添加到对象:[[prototype]]
Object.setPrototypeOf()
let a = {};
// a now has all the properties of Array.prototype
Object.setPrototypeOf(a, Array.prototype);
a.push('foo');
console.log(a);
let b = Object.preventExtensions({});
// must not be able add properties to b in the same way
Object.setPrototypeOf(b, Array.prototype);
b.push('bar');
console.log(b);
推荐阅读
- php - PHP - ip2long 没有正确转换
- laravel - 仅在自有模型上验证 unique()
- php - 在 laravel 中使用联合和分页从子查询中选择
- macos - macOS 使用 CGContextRef 并且总是黑色
- math - 将 20 个值拟合为 5 位
- ios - 没有用 AVPLayer 播放视频
- java - 如何在java中执行创建触发器sql?
- excel - VBA - 数组公式:formulaArray 上的运行时错误 1004,即使公式看起来正确。里面的例子
- python - 在通道维度连接两个图像?
- python - django.db.utils.InterfaceError: (0, '')