Object.seal()
Object.seal() 静态方法会密封一个对象。密封一个对象会阻止其添加新属性,并使现有属性不可配置。一个被密封的对象拥有固定数量的属性:不能添加新属性,不能删除现有属性,也不能更改其可枚举性和可配置性,也不能重新分配其原型。只要属性是可写的,其值仍然可以被更改。seal() 返回传入的同一个对象。
试一试
const object = {
foo: 42,
};
Object.seal(object);
object.foo = 33;
console.log(object.foo);
// Expected output: 33
delete object.foo; // Cannot delete when sealed
console.log(object.foo);
// Expected output: 33
语法
js
Object.seal(obj)
参数
obj-
需要被密封的对象。
返回值
被密封的对象。
描述
密封一个对象相当于阻止添加新属性,然后将所有现有属性的描述符更改为 configurable: false。这样做的效果是使对象上的属性集固定不变。将所有属性设置为不可配置也会阻止它们从数据属性转换为访问器属性,反之亦然,但它不会阻止数据属性的值被更改。尝试删除或添加属性到被密封的对象,或者将数据属性转换为访问器属性(反之亦然)将失败,可能是静默失败,也可能抛出 TypeError(最常见,但不限于,在严格模式代码中)。
私有元素不是属性,也没有属性描述符的概念。无论对象是否被密封,私有元素都无法从对象中添加或删除。
原型链保持不变。然而,由于阻止添加新属性的效果,[[Prototype]] 无法被重新赋值。
与Object.freeze() 不同,使用 Object.seal() 密封的对象,只要其现有属性是可写的,其值仍然可以被更改。
示例
使用 Object.seal
js
const obj = {
prop() {},
foo: "bar",
};
// New properties may be added, existing properties
// may be changed or removed.
obj.foo = "baz";
obj.lumpy = "woof";
delete obj.prop;
const o = Object.seal(obj);
o === obj; // true
Object.isSealed(obj); // true
// Changing property values on a sealed object
// still works.
obj.foo = "quux";
// But you can't convert data properties to accessors,
// or vice versa.
Object.defineProperty(obj, "foo", {
get() {
return "g";
},
}); // throws a TypeError
// Now any changes, other than to property values,
// will fail.
obj.quaxxor = "the friendly duck";
// silently doesn't add the property
delete obj.foo;
// silently doesn't delete the property
// … and in strict mode such attempts
// will throw TypeErrors.
function fail() {
"use strict";
delete obj.foo; // throws a TypeError
obj.sparky = "arf"; // throws a TypeError
}
fail();
// Attempted additions through
// Object.defineProperty will also throw.
Object.defineProperty(obj, "ohai", {
value: 17,
}); // throws a TypeError
Object.defineProperty(obj, "foo", {
value: "eit",
}); // changes existing property value
非对象参数
在 ES5 中,如果传递给此方法的参数不是对象(而是原始类型),则会引发 TypeError。在 ES2015 中,非对象参数将被原样返回,不会出现任何错误,因为原始类型本身就是不可变的。
js
Object.seal(1);
// TypeError: 1 is not an object (ES5 code)
Object.seal(1);
// 1 (ES2015 code)
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-object.seal |
浏览器兼容性
加载中…