Home > Web Front-end > JS Tutorial > How to create immutable objects in js

How to create immutable objects in js

王林
Release: 2020-05-19 09:16:03
forward
2784 people have browsed it

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
};
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template