protection
Object.preventExtensions
Prevents new properties from being added to an object, but existing properties can still be modified, deleted, or reconfigured. The weakest of the three protection levels.
Object.preventExtensions(obj) Parameters
| Parameter | Purpose |
|---|---|
| obj | The object to make non-extensible |
| returns | The same (now non-extensible) object |
Examples
const o = Object.preventExtensions({ a: 1 });
try { o.b = 2; } catch (e) {}
console.log(o.b); Logs undefined — new property rejected
const o = Object.preventExtensions({ a: 1 });
o.a = 99;
delete o.a;
console.log(o.a); Logs undefined — existing properties are still mutable and deletable
console.log(Object.isExtensible(Object.preventExtensions({}))); Logs false
const o = Object.preventExtensions({});
try { Object.setPrototypeOf(o, { p: 1 }); } catch (e) { console.log(e.name); } Logs 'TypeError' — the prototype is also locked
Gotcha
Also prevents changing the prototype via setPrototypeOf. Weaker than seal (which additionally makes properties non-configurable) and freeze (which additionally makes data properties non-writable).
Related methods
Object.isExtensible
Returns true if new properties can be added to the object. Sealed, frozen, and preventExtensions'd objects all return false; primitives always return false.
Object.seal
Seals an object: prevents new properties from being added and marks all existing properties as non-configurable. Existing writable properties can still be reassigned.
Object.freeze
Freezes an object: new properties cannot be added, existing properties cannot be removed, and their values, writability, and configurability cannot be changed. Returns the same object.
Object.isFrozen
Returns true if the object is frozen — non-extensible, and every own property is non-configurable and (if a data property) non-writable. Primitives are considered frozen.
Object.isSealed
Returns true if the object is sealed — non-extensible and all own properties are non-configurable. Frozen objects are always sealed; primitives are considered sealed.