Viki 写东西的地方


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!


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.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 };


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 };

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.

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