Home > Article > Web Front-end > How to create immutable objects in js
Immutability of objects means that we do not want the objects to change in any way after they are created (setting them to a read-only type).
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 modified incorrectly.
const myTesla = { maxSpeed: 155, batteryLife: 300, weight: 2300 };
Object.preventExtensions() Prevent extension
This method prevents adding new properties to existing objects, preventExtensions() is an irreversible operation, we can never Add additional properties to the object.
Object.isExtensible(myTesla); // true Object.preventExtensions(myTesla); Object.isExtensible(myTesla); // false myTesla.color = 'blue'; console.log(myTesla.color) // undefined
Object.seal() seal
It can prevent the addition or deletion of attributes. seal() can also prevent the modification of the attribute descriptor.
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, 'batteryLife'); // TypeError: Cannot redefine property: batteryLife
Object.freeze() Freeze
It has the same effect 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, 'batteryLife'); // 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 to create immutable objects in js. For more information, please follow other related articles on the PHP Chinese website!