The immutability of objects means that we don’t want objects to change in any way after creation (making them read-only types).
Suppose we need to define a car object and use its properties throughout the project to perform operations. We cannot allow any data to be incorrectly modified.
const myTesla = { maxSpeed: 155, batteryLife: 300, weight: 2300 };
Object.preventExtensions() prevents extensions
This method prevents adding new properties to existing objects, preventExtensions() is an irreversible operation, We can never add extra properties to objects again.
Object.isExtensible(myTesla); // true Object. preventExtensions(myTesla); Object. isExtensible(myTesla); // false myTesla.color = 'blue'; console.log(myTesla.color) // undefined
Object.seal() seals
It prevents adding or removing properties, seal() also Can prevent property descriptors from being modified.
Object.isSealed(myTesla); // false Object. seal(myTesla); Object.isSealed(myTesla); // true myTesla.color = 'blue'; console.log(myTesla.color); // undefined delete myTesla. batteryLife; // false console.log(myTesla.batteryLife); // 300 Object.defineProperty(myTesla, & #39;batteryLife'); // TypeError: Cannot redefine property: batteryLife
Object.freeze() Freeze
It works the same as Object.seal(), and it makes the property unwritable.
Object.isFrozen(myTesla); // false Object. freeze(myTesla); Object.isFrozen(myTesla); // true myTesla.color = 'blue'; console.log(myTesla.color); // undefined delete myTesla. batteryLife; console.log(myTesla.batteryLife); // 300 Object.defineProperty(myTesla, & # 39; batteryLife & # 39;); // TypeError: Cannot redefine property: batteryLife myTesla. batteryLife = 400; console.log(myTesla.batteryLife); // 300
Note: If you want an error to be thrown when trying to modify an immutable object, use strict mode.
Recommended tutorial: js introductory tutorial
The above is the detailed content of how js creates immutable objects. For more, please pay attention to other related articles on 1024programmer.com!