Object.freeze() vs Object.seal() vs Object.preventExtensions()
Methods seal, freeze, preventExtensions are used to make any object immutable.
Object.freeze()
The Object.freeze() method freezes an object.
1) Prevents adding new properties
2) Doesn’t allow remove existing properties
3) Does not allow to change immediate properties of object
4) Attributes of child objects can be modified
let obj = {
firstName:"sangram",
add:{
city:"mumbai"
}
}
Object.freeze(obj)
obj.firstName = "sagar"
delete obj.firstName
obj.lastName ="desai"
obj.add.city = "pune"
console.log("isFrozen",Object.isFrozen(obj))
console.log(obj)
Output:
isFrozen true
{ firstName: 'sangram', add: { city: 'pune' } }
Adding new property failed,deleting exiting property failed,modifying existig property fail ,updating child object property succeeded
we can freeze the arrays in JavaScript by using Object.freeze().
var a=["sagar","sangram"]
Object.freeze(a)
a.push("sanket")
GOT Error TypeError: Cannot add property 2, object is not extensible
Object.seal:
Seal method preventing new properties from being added to the object.
Allows changing existed properties of an object
Prevents adding new properties
Don’t allow remove existing properties
let obj = {
firstName:"sangram",
add:{
city:"mumbai",
state:"maharashtra"
}
}
Object.seal(obj)
obj.firstName = "sagar"
delete obj.firstName
obj.lastName ="desai"
obj.add.city = "pune"
delete obj.add.state
console.log("isSealed",Object.isSealed(obj))
console.log(obj)
Output:
isSealed true
{ firstName: 'sagar', add: { city: 'pune' } }
allowed to change child property & delete child property
Object.preventExtensions():
The Object.preventExtensions() method prevents new properties
from ever being added to an object (i.e. prevents future extensions
to the object). It does the following things:
Allows changing existed properties of an object
Prevents adding new properties
Feature | Default | Freeze | Seal | PreventExtension |
Add New Property | Yes | No | No | No |
Remove Existing Property | Yes | No | No | Yes |
Change Existing Property Value | Yes | No | Yes | Yes |
Modify Child Property | Yes | Yes | Yes | Yes |
No comments:
Post a Comment