首页 > 解决方案 > 为什么将对象设置为不可扩展使其 [[prototype]] 不可变?

问题描述

MDN - Object.preventExtensions页面说

此方法使[[prototype]]目标的 不可变;任何[[prototype]]重新分配都会抛出一个TypeError. 此行为特定于内部[[prototype]]属性,目标对象的其他属性将保持可变。

我的问题是:

为什么将对象设置为不可扩展使其 [[prototype]] 不可变?( Object.preventExtensions(),Object.seal()Object.freeze())

标签: javascript

解决方案


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


推荐阅读