我正在浏览 MDC 关于添加到 Object 的新功能。其中之一,Object.preventExtensions
,据说可以防止对象原型的突变,可以通过使用Object.getPrototypeOf
或获得__proto__
。
然而,在 Chrome 上,它似乎只是允许对对象的原型进行更改。这可以通过执行相关页面上的代码来确认:
// EXTENSION (only works in engines supporting __proto__
// (which is deprecated. Use Object.getPrototypeOf instead)):
// A non-extensible object's prototype is immutable.
var fixed = Object.preventExtensions({});
fixed.__proto__ = { oh: "hai" }; // throws a TypeError
我不明白这个TypeError
, and fixed.__proto__.oh === 'hai'
, 所以它已经被设置了,即使它应该被禁止。我也可以在编码时添加它Object.getPrototypeOf(fixed).oh = 'hai'
。
这是否意味着 Chrome 对这个功能有不同的解释?如何防止扩展对象原型(在 Chrome 中)?