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 |
瀏覽器相容性
載入中…