JS: Object.preventExtensions

JS: Object.preventExtensions


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 = {};


); // false

// add a property
uu.pp = 3;

); // 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};


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

delete t.p;

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

[see JS: Property Attributes, writable, enumerable, configurable]


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

[see JS: Reflect.preventExtensions]


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

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog