試一試
const object = {
foo: 42,
};
console.log(Object.isSealed(object));
// Expected output: false
Object.seal(object);
console.log(Object.isSealed(object));
// Expected output: true
語法
js
Object.isSealed(obj)
引數
obj-
需要檢查的物件。
返回值
一個 Boolean 值,指示給定的物件是否被 seal 了。
描述
如果物件被 seal 了,則返回 true,否則返回 false。一個物件被 seal 了,意味著它不再是 extensible(不可擴充套件)的,並且其所有屬性都是不可配置的,因此不能被刪除(但並非一定不可寫)。
示例
使用 Object.isSealed
js
// Objects aren't sealed by default.
const empty = {};
Object.isSealed(empty); // false
// If you make an empty object non-extensible,
// it is vacuously sealed.
Object.preventExtensions(empty);
Object.isSealed(empty); // true
// The same is not true of a non-empty object,
// unless its properties are all non-configurable.
const hasProp = { fee: "fie foe fum" };
Object.preventExtensions(hasProp);
Object.isSealed(hasProp); // false
// But make them all non-configurable
// and the object becomes sealed.
Object.defineProperty(hasProp, "fee", {
configurable: false,
});
Object.isSealed(hasProp); // true
// The easiest way to seal an object, of course,
// is Object.seal.
const sealed = {};
Object.seal(sealed);
Object.isSealed(sealed); // true
// A sealed object is, by definition, non-extensible.
Object.isExtensible(sealed); // false
// A sealed object might be frozen,
// but it doesn't have to be.
Object.isFrozen(sealed); // true
// (all properties also non-writable)
const s2 = Object.seal({ p: 3 });
Object.isFrozen(s2); // false
// ('p' is still writable)
const s3 = Object.seal({
get p() {
return 0;
},
});
Object.isFrozen(s3); // true
// (only configurability matters for accessor properties)
非物件引數
在 ES5 中,如果傳遞給此方法的引數不是一個物件(即原始型別),則會丟擲 TypeError。在 ES2015 中,如果傳遞了非物件引數,則會直接返回 true 而不丟擲任何錯誤,因為原始型別按定義是不可變的。
js
Object.isSealed(1);
// TypeError: 1 is not an object (ES5 code)
Object.isSealed(1);
// true (ES2015 code)
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-object.issealed |
瀏覽器相容性
載入中…