JS: Prevent Adding Property
Objects have internal slot “IsExtensible” that indicates if properties can added to the object.
(Note, in ES5.1 (year 2011), this was called “Extensible”. It's renamed to “IsExtensible” in ES2015.)
Object's properties have attribute
writable that determines if a property can be changed, and the attribute
configurable determines if a property can be deleted,
Object's extensible attribute and property attributes together determine if property can be added to the object, deleted, or if their values can be modified.
Note: if a object is not extensible, but its parents may be, so people can add properties to the parent object, and your object may still get unexpected properties, because of inheritance.
What Objects Are Extensible?
- User-defined objects are extensible, by default.
- Standard objects (For example, Object, Array, Function, Date, …) are extensible, by default.
- Host objects (For example,
windows.document) may or may not be extensible.
const arr = [ Object, Array, Function , String , Date, RegExp ]; console.log ( arr . every (x => Object.isExtensible(x) ) ); // true
[see JS: Object Type]
Check If Object is Extensible
[see JS: Object.isExtensible]
Prevent Adding Properties
Prevent Adding/Deleting Properties
[see JS: Object.seal]
[see JS: Object.isSealed]
Prevent Adding/Deleting/Writing Properties
[see JS: Object.freeze]
[see JS: Object.isFrozen]
Object and Inheritance Topic
- JS: Object Overview
- JS: Object Type
- JS: Determine Type of Object
- JS: Object Literal Expression
- JS: Prototype and Inheritance
- JS: Create Object
- JS: Create Object with Parent X
- JS: Get/Set Prototype
- JS: Prevent Adding Property
- JS: Clone, Deep Copy Object/Array
- JS: Test Equality of Objects
- JS: Object Object
- JS: Object.prototype
If you have a question, put $5 at patreon and message me.