Object.preventExtensions()

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

Chrome6
Edgeyes
Firefox4
Internet Explorer9
Opera12
Safari5.1
Android webviewyes
Chrome for Androidyes
Edge mobileyes
Firefox for Android4
Opera Androidyes

One thought on “Object.preventExtensions()

Add yours

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started