Creating immutable objects in native JavaScript —— 在原生JavaScript中创建不可变对象

Javascript it’s a flexible language, you can redefine anything. But when projects get complex we find problems with mutable data structures. With the latest versions of JavaScript this situation changed. Now it’s possible to create immutable objects. I’ll walk you through how to do it in three different ways.

Javascript是一种灵活的语言,您可以重新定义任何内容。但是,当项目变得复杂时,我们会发现可变数据结构存在问题。使用最新版本的JavaScript,这种情况发生了变化。现在可以创建不可变的对象。我将以三种不同的方式指导您完成操作。

Immutability in object means we don’t want our objects to change in any ways once we create them i.e make them read-only type.

对象的不变性意味着一旦创建对象,即使它们成为只读类型,我们就不希望对象发生任何变化。

Let’s suppose we need to define a car Object and use its properties to perform operations throughout our entire project. We can’t allow modifying by mistake any data.

假设我们需要定义一个汽车对象,并使用其属性在整个项目中执行操作。我们不允许错误地修改任何数据。

const myTesla = {
	maxSpeed: 155,
	batteryLife: 300,
	weight: 2300
};

Object.preventExtensions()

This method prevents the addition of new properties to our existing object. preventExtensions() is a irreversible operation. We can never add extra properties to the object again.

此方法可防止向现有对象添加新属性。 preventExtensions()是不可逆的操作。我们永远不能再向对象添加额外的属性。

Object.isExtensible(myTesla); // true
Object.preventExtensions(myTesla);
Object.isExtensible(myTesla); // false
myTesla.color = 'blue';
console.log(myTesla.color) // undefined

Object.seal()

It prevents additions or deletion of properties. seal() also prevents the modification of property descriptors.

它防止添加或删除属性。seal()还防止修改属性描述符。

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()

It does the same that Object.seal() plus it makes the properties non-writable.

它的作用与Object.seal()使属性不可写相同。

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

Others

Use strict mode if you want to throw an error when trying to modify an immutable object.

strict mode如果要在尝试修改不可变对象时抛出错误,请使用此方法。



For study use only,translation from loverajoel.

猜你喜欢

转载自blog.csdn.net/SmallTeddy/article/details/108491470