Object.seal()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

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

瀏覽器相容性

另見