Why Object.preventExtensions ?
New property can be added to an object from the outside. There are many ways. If we want to avoid adding new features to the object, we should use the Object.preventExtensions () method. This method prevents the addition of new elements to the object. This change is permanent, that is, when an object is made irreversible, it becomes non-expandable.
This method makes the [[prototype]] value of the target unchangeable; [[prototype]] assigns a TypeError to reassignments. This behavior is specific to the internal [[prototype]] property, other properties of the target object will remain variable.
Syntax:
Object.preventExtensions( obj )
obj (required): The object to make non-extensible.
Return Value
It returns the object being made non-extensible.
JavaScript Object.preventExtensions Examples
Example 1
If false is returned when the isExtensible () method is applied, the object is unchangeable. If it returns true, the object is interchangeable.
let animal1 = {
animal: "cat",
name: "minos"
}
Object.preventExtensions(animal1);
console.log(Object.isExtensible(animal1));
let animal2 = {
animal: "cat",
name: "minos"
}
console.log(Object.isExtensible(animal2));
output:
false
true
Example 2
let people = {
person1: "alex",
person2: "rick",
person3: "maria"
}
console.log("preventExtensions: " + Object.isExtensible(people));
people.person4 = "oliver";
console.log(people);
Object.preventExtensions(people);
console.log("preventExtensions: " + Object.isExtensible(people));
people.person5 = "barry";
console.log(people);
output:
preventExtensions: true
{person1: “alex”, person2: “rick”, person3: “maria”, person4: “oliver”}
preventExtensions: false
{person1: “alex”, person2: “rick”, person3: “maria”, person4: “oliver”}
Sources:
Browser Support
| Chrome | 6 |
| Edge | yes |
| Firefox | 4 |
| Internet Explorer | 9 |
| Opera | 12 |
| Safari | 5.1 |
| Android webview | yes |
| Chrome for Android | yes |
| Edge mobile | yes |
| Firefox for Android | 4 |
| Opera Android | yes |