1024programmer JavaScript js how to create immutable objects

js how to create immutable objects

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!

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/js-how-to-create-immutable-objects/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索