Home >Web Front-end >JS Tutorial >How to use the Object.freeze() method in JavaScript
In the Object constructor method, there is an Object.freeze() method, which is used to freeze the object. Freezing an object disallows new properties from being added to the object and prevents existing properties from being deleted or changed. Next we will introduce how to use the Object.freeze() method, I hope it will be helpful to everyone.
Object.freeze() method
The Object.freeze() method takes an object as a parameter , freezes this object; it preserves the object's enumerability, configurability, writability, and prototype from being modified; it returns the frozen object, but does not create a frozen copy. [Recommended related video tutorials: JavaScript Tutorial]
Basic syntax:
Object.freeze(obj)
bject.freeze() method Using
Let’s take a simple example to see how to use the object.freeze() method.
Example 1: Freeze an object or array
var obj1 = { name: '小华',age:'20岁'}; var obj2 = Object.freeze(obj1); console.log(obj2); obj2.name = '小明'; obj2.sex = '男'; console.log(obj2);
Output:
Example description:
Use the Object.freeze() method to freeze the obj1 object, and then assign the properties in the frozen obj1 object to the obj2 object; because the obj1 object is frozen, new properties and values are prevented from being added to the obj2 object.
Example 2: Making an object immutable
var obj = { prop: function() {}, name: '小明' }; console.log(obj); obj.name = '李华'; delete obj.prop; console.log(obj); var o = Object.freeze(obj); obj.name = 'chris'; console.log(obj);
Output:
Example description:
The obj object is assigned the attribute [prop, function() {}] pair and the [name, adam] pair. Because the obj object has not been frozen at this time, you can delete "prop: function", modify the value of the name attribute to 'Li Hua'.
The new object "o" is assigned the frozen value of "obj". Because the obj1 object is frozen, it will prevent the modification of attributes and values, so the value of the name attribute is still 'Li Hua'.
The above is the entire content of this article, I hope it will be helpful to everyone's study.
The above is the detailed content of How to use the Object.freeze() method in JavaScript. For more information, please follow other related articles on the PHP Chinese website!