试一试
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 |
浏览器兼容性
加载中…