Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Kiểm tra object đã được seal trong JavaScript

Object.isSealed() trả về true nếu object thỏa mãn 2 điều kiện:

  1. Non-extensible: Không thể thêm property mới (Object.preventExtensions() hoặc Object.seal()/freeze()).
  2. 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ứcExtensibleConfigurable propsWritable propsisSealedisFrozen
Object.preventExtensions()NoGiữ nguyênGiữ nguyênfalsefalse
Object.seal()NoNoGiữ nguyêntruefalse
Object.freeze()NoNoNotruetrue

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.