What is the Object.preventExtensions() method in Javascript?
The preventExtensions() method of the Object class in Javascript prevents objects from gaining new properties.
The process is illustrated below:
To use the preventExtensions() method, you will need to use the following command:
Object.preventExtensions(anyObj);
In the code shown above, anyObj represents an instance of the Object class.
Parameters
The preventExtensions() method takes a single mandatory parameter, i.e., the object to be made non-extensible.
Return value
The preventExtensions() method returns a non-extensible object. New properties can no longer be added to the object.
Example
The code below shows how the preventExtensions() method works in Javascript:
// initialize objectconst myObj = {};// check if extensibleconsole.log("Can the object be extended? ", Object.isExtensible(myObj));// add new propertytry{Object.defineProperty(myObj, 'property1', {value: 5});console.log("New property added.")}catch (error){console.log(error.message);}// make object non-extensibleObject.preventExtensions(myObj);// check if extensibleconsole.log("Can the object be extended? ", Object.isExtensible(myObj));// add new propertytry{Object.defineProperty(myObj, 'property2', {value: 10});console.log("New property added.")}catch (error){console.log(error.message);}
Explanation
First, an empty object myObj is initialized. The isExtensible() method is called to check if new properties can be added to myObj. Since objects are extensible by default, the isExtensible() method returns true.
The defineProperty() method in line adds a new property to myObj. Since the object is extensible, the defineProperty() method does not throw an error.
Next, the preventExtensions() method in line proceeds to make myObj a non-extensible object. As a result, new properties can no longer be added to it. The isExtensible() method in line returns false, which confirms that myObj is non-extensible.
Finally, the defineProperty() method in line attempts to add a new property to myObj. However, myObj is now a non-extensible object, so an error is thrown. The error triggers the catch branch of the try-catch block, and the error message is output.
Free Resources