Object.isSealed() trả về true nếu object thỏa mãn 2 điều kiện:
- Non-extensible: Không thể thêm property mới (
Object.preventExtensions()hoặcObject.seal()/freeze()). - Non-configurable properties: Tất cả property hiện tại đều
configurable: false(không xóa, không đổi descriptor).
Cú pháp
Object.isSealed(obj); // true / false
Ví dụ: Object thường — chưa seal
<script>
const obj = { prop1: 2 };
document.write(Object.isSealed(obj)); // false
</script>
Ví dụ: Object đã seal
<script>
const obj = { prop1: 2 };
Object.seal(obj); // Seal: non-extensible + non-configurable props
document.write(Object.isSealed(obj)); // true
// Thử thêm property — thất bại (strict mode throw error)
obj.newProp = 3;
document.write(obj.newProp); // undefined
// Thử xóa property — thất bại
delete obj.prop1;
document.write(obj.prop1); // 2 — vẫn còn
// Nhưng CÓ THỂ thay đổi value
obj.prop1 = 20;
document.write(obj.prop1); // 20
</script>
So sánh: Seal vs Freeze vs PreventExtensions
| Phương thức | Extensible | Configurable props | Writable props | isSealed | isFrozen |
|---|---|---|---|---|---|
| Object.preventExtensions() | No | Giữ nguyên | Giữ nguyên | false | false |
| Object.seal() | No | No | Giữ nguyên | true | false |
| Object.freeze() | No | No | No | true | true |
Kiểm tra liên quan
Object.isExtensible(obj); // true/false — có thêm property mới được không
Object.isFrozen(obj); // true/false — seal + writable: false
Lưu ý
seal()vàfreeze()là shallow — chỉ áp dụng level 1, nested object vẫn có thể thay đổi.- Trong non-strict mode, vi phạm seal/freeze thất bại thầm; strict mode → throw TypeError.