
JavaScript Basics: Object.preventExtensions and Object.isExtensible
In JavaScript, an object is extensible by default. This means that new properties can be added to the object. In some circumstances, you my want to prevent extensions to the object. To this end, you can use Object.preventExtensions. This function prevents any extensions to the object, so that no new property can be added to the object. If you try to add new properties to the object, it will cause a TypeError (or fail silently if not in strict mode).
Here is an example:
let myObj = {
name: "Ali",
};
Object.isExtensible(myObj); // true
Object.preventExtensions(myObj);
Object.isExtensible(myObj); // false
myObj.age = 19; // fails silently
myObj.age; // undefined
It should be noted that after making an object inextensible, its __proto__ property becomes immutable. In other words, you cannot assign a new value to the __proto__ property. However, if the prototype is extensible, you can add new properties to the prototype.
As the EcmaScript standard attempts to organize the global objects, this functions are also available on the Reflect global object. So you can use Reflect.isExtensible and Reflect.preventExtensions instead.
Related Posts
Leave JavaScript Basics: Object.preventExtensions and Object.isExtensible to:
Read more #javascript posts
Best Posts From ghasemkiani
We have not curated any of ghasemkiani's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From ghasemkiani
- Merging PDF Files with Java
- Happy Iranian New Year
- Stephen Hawking, one of the greatest physicists of our time, dies at 76
- Using Scoped NPM Packages
- Optimistic Typing in Nashorn
- JavaScript Basics: Reflect.apply
- JavaScript Basics: Reflect.construct
- JavaScript Basics: Reflect
- New Horizons Broke the Record of the “Pale Blue Dot” Picture
- JavaScript Basics: Object.freeze and Object.isFrozen
- JavaScript Basics: Object.seal and Object.isSealed
- JavaScript Basics: Object.preventExtensions and Object.isExtensible
- JavaScript Basics: Object.prototype.hasOwnProperty
- JavaScript Basics: Object.is
- JavaScript Basics: Object.keys, Object.values, and Object.entries
- What Is Success and How Do You Define It?
- Steemit Reached 700,000 Members
- JavaScript Basics: Object.getPrototypeOf and Object.setPrototypeOf
- JavaScript Basics: Object.assign
- JavaScript Basics: Object.create