Object.preventExtensions()
静态方法 Object.preventExtensions() 可阻止新属性被添加到对象(即阻止对象的未来扩展)。它还会阻止对象的原型被重新分配。
试一试
const object = {};
Object.preventExtensions(object);
try {
Object.defineProperty(object, "foo", {
value: 42,
});
} catch (e) {
console.log(e);
// Expected output: TypeError: Cannot define property foo, object is not extensible
}
语法
js
Object.preventExtensions(obj)
参数
obj-
要使其不可扩展的对象。
返回值
被使其不可扩展的对象。
描述
如果可以向对象添加新属性,则该对象是可扩展的。Object.preventExtensions() 将对象标记为不再可扩展,因此它永远不会拥有比标记为不可扩展时更多的属性。请注意,不可扩展对象的属性通常仍可被删除。尝试向不可扩展对象添加新属性将失败,可能会静默失败,或者在严格模式下抛出TypeError。
与Object.seal() 和Object.freeze() 不同,Object.preventExtensions() 调用的是 JavaScript 的内在行为,不能与其他多个操作组合替代。它还有一个对应的Reflect 方法(仅适用于内在操作),即Reflect.preventExtensions()。
Object.preventExtensions() 仅阻止添加自身属性。属性仍可以添加到对象原型。
此方法使目标对象的 [[Prototype]] 不可变;任何 [[Prototype]] 的重新分配都将抛出 TypeError。此行为是针对内部 [[Prototype]] 属性的;目标对象的其他属性将保持可变。
一旦对象被设为不可扩展,就无法再使其变得可扩展。
示例
使用 Object.preventExtensions
js
// Object.preventExtensions returns the object
// being made non-extensible.
const obj = {};
const obj2 = Object.preventExtensions(obj);
obj === obj2; // true
// Objects are extensible by default.
const empty = {};
Object.isExtensible(empty); // true
// They can be made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false
// Object.defineProperty throws when adding
// a new property to a non-extensible object.
const nonExtensible = { removable: true };
Object.preventExtensions(nonExtensible);
Object.defineProperty(nonExtensible, "new", {
value: 8675309,
}); // throws a TypeError
// In strict mode, attempting to add new properties
// to a non-extensible object throws a TypeError.
function fail() {
"use strict";
// throws a TypeError
nonExtensible.newProperty = "FAIL";
}
fail();
不可扩展对象的原型是不可变的
js
const fixed = Object.preventExtensions({});
// throws a 'TypeError'.
fixed.__proto__ = { oh: "hai" };
非对象参数
在 ES5 中,如果此方法的参数不是对象(原始值),则会导致 TypeError。在 ES2015 中,非对象参数将按原样返回,不会出现任何错误,因为根据定义,原始值已经是不可变的。
js
Object.preventExtensions(1);
// TypeError: 1 is not an object (ES5 code)
Object.preventExtensions(1);
// 1 (ES2015 code)
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-object.preventextensions |
浏览器兼容性
加载中…