Viki

Viki 写东西的地方

努力上进且优秀
x
github
email
bilibili

Object methods: `freeze` vs `seal` vs `preventExtensions`

When we enter the world of JavaScript, we will encounter three mysterious companions: freeze, seal, and preventExtensions. They are like talismans that protect our objects from external harm, but they each have their own differences!

Object.freeze()#

This old man is a true frost mage! Once you use Object.freeze(), your object will be frozen and unable to add new properties or modify the writability and configurability of existing properties, let alone delete properties! It's like putting your object in an ice age, forever motionless.

You can use Object.isFrozen to determine if it has been frozen.

const icyObj = { chill: "frosty" };
Object.freeze(icyObj);

Object.seal()#

Object.seal() is more like putting a bulletproof vest on your object than freezing it. You can still change the values of existing properties, but you cannot add new properties or delete existing ones. It's like putting your object in a tight-fitting suit, protecting it from external harm.

You can use Object.isSealed to determine if it has been sealed.

const bulletproofObj = { strong: true };
Object.seal(bulletproofObj);

Object.preventExtensions()#

Oh, Object.preventExtensions() is a bit more lenient. It only prevents you from adding new properties to the object, but you can still modify and delete existing properties. It's like drawing a boundary line for your object and telling you, "Hey, buddy, you can't expand anymore!"

You can use Object.isExtensible to determine if it has been prevented from extensions.

const extendableObj = { flexible: true };
Object.preventExtensions(extendableObj);

These methods may be obscure, but they can protect your precious objects from external destruction. Please remember them, as if you are putting thick protective clothing on your objects in a cold world!

Article generated and polished by ChatGPT.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.