JS: Object.preventExtensions

JS: Object.preventExtensions

Object.preventExtensions(obj)

Make it impossible to add properties to object obj.

Return obj.

Note: once a object is not extensible, you cannot revert it.

Note: it also return obj if obj is not a object type, such as a number 3.

[see JS: Prevent Adding Property]

// set the extensible attribute of a object to false

const uu = {};

Object.preventExtensions(uu);

console.log(
    Object.isExtensible(uu)
); // false

// add a property
uu.pp = 3;

console.log(
    uu.hasOwnProperty("pp")
); // false

Note: if a object is not extensible, but its parents may be, so you can add properties to the parent object, and your object may still get unexpected properties, because of inheritance.

Non-Extensible object's property can still be deleted.

// non-extensible object's property can still be deleted

const t = {"p":3};

Object.preventExtensions(t);

console.log ( t.hasOwnProperty ( "p" ) ); // true

delete t.p;

console.log ( t.hasOwnProperty ( "p" ) ); // false

[see JS: Property Attributes]

Reflect.preventExtensions

If using ES2015, you should use Reflect.preventExtensions instead.

[see JS: Reflect.preventExtensions]

Reference

ECMAScript® 2016 Language Specification#sec-invariants-of-the-essential-internal-methods

ECMAScript® 2016 Language Specification#sec-object.preventextensions

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth