1. Basic concepts
Object invariance is an important concept in any programming language. It restricts object modifications and prevents unwanted changes. In short, the invariance of an object is to turn its state into read-only. Let’s take a look at the invariance of an object in JavaScript.
existJavaScript
In , an object can have one or more properties. Each attribute is a key-value pair.
Here is an object:
const user = { name: 'CUGGZ', age: 24, }
Used hereconst
A keyword defines an object that has two properties. By default, objects are mutable, that is, we can add new properties to the object, modify existing properties, or delete existing properties. In some cases, we may want the object to be immutable, that is, we cannot add new attributes, nor can we modify and delete existing attributes.
2. ()
As the name implies,freeze()
It is used to freeze objects. Just pass the object you don't want to be changed to it, and the immutable version of the object will be returned:
const user = { name: 'CUGGZ', age: 24, } const freezeUser = (user); = 18; () // 24
At this time, the new object cannot be changed, which is equivalent to being frozen.
existJavaScript
It provides a()
, it can be used to determine whether an object is frozen:
(user) // false (freezeUser) // true
It should be noted that()
Methods will not affect nested objects, and for nested objects, they can still be operated after freezing:
const user = { name: 'CUGGZ', age: 24, article: { title: 'learn javascript', number: 1234 } } const freezeUser = (user); = 18 = 666; () // 24 (); // 666
You can see, use()
The object frozen by the method cannot be changed, but the object nestednumber
The properties can still be modified. If you need to freeze nested objects to make them immutable, you need to use loop recursion to freeze step by step. Here is a simple recursive freeze implementation:
const deepFreeze = obj => { (obj).forEach(prop => { if (typeof obj[prop] === 'object') { deepFreeze(obj[prop]); } }); return (obj); }; deepFreeze(user);
()
In addition to freezing objects, methods can also be used to freeze arrays to make them immutable:
const number = [1, 2, 3, 4, 5]; const freezeNumber = (number); (6);
An error will be reported at this time:
VM210:3 Uncaught TypeError: Cannot add property 5, object is not extensible
3. ()
()
As the name implies, it is to seal an object, it is another way to make an object immutable. Compared to freeze(), the() method only protects the object from adding and removing properties, which allows the existing properties to be updated.
const user = { name: 'CUGGZ', age: 24, } const sealUser = (user); = 18; delete ; (sealUser) // {name: 'CUGGZ', age: 18}
You can see that we recognize the image and delete the objectname
Attribute, the deletion failed; and modify the existing age attribute, the modification was successful.
()
Methods and()
Similarly, it is impossible to implement immutable for nested objects. If you want to implement them, you also need to use recursion to seal the objects layer by layer.
JavaScript also provides a()
Method to confirm the sealing status of the object:
(user) // false (sealUser) // true
4. Const keyword?
Do you think that using the const keyword can achieve the same result? In fact, they are different when we useconst
When a keyword is used to create an object, it prevents us from reassigning values, but we can update, add, and delete properties of existing objects:
const user = { name: 'CUGGZ', age: 24, } delete ; = 180; = 'hello'; (user); // {name: 'hello', height: 180}
And if we reassign the user, then an error will be reported:
Uncaught TypeError: Assignment to constant variable.
Therefore, the const keyword only provides invariance of the assignment, and does not provide invariance of the value (for the object).
5. Summary
This article briefly introduces two types of information that can be used to makeJavaScript
Immutable method. in short,()
Methods prevent new attributes from being updated, deleted, and adding new attributes to objects, () will only prevent the addition and deleted attributes. ,
besides,JavaScript
Also provided is a()
Method, this method can make an object unscalable, that is, new attributes can never be added.
const user = { name: 'CUGGZ', age: 24, } const newUser = (user); = 180; (newUser); // {name: 'CUGGZ', age: 24}
Finally, let’s take a look at the comparison of the three of them:
Methods/Operations | Read | create | renew | delete |
---|---|---|---|---|
() | ✔️ | ❌ | ❌ | ❌ |
() | ✔️ | ❌ | ✔️ | ❌ |
() | ✔️ | ❌ | ✔️ | ✔️ |
This is the end of this article about the invariance of JavaScript objects. For more related content on JavaScript objects, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!