Object preventExtension vs seal vs freeze
source link: https://til.cybertec-postgresql.com/post/2019-10-11-Object-preventExtension-vs-seal-vs-freeze/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Object preventExtension vs seal vs freeze
2019-10-11
ECMAScript 5 introduced new Object
methods to Javascript. Among them preventExtensions
, seal
, freeze
methods will be compared to each other.
preventExtensions
An object called by this method can't have any new properties being added.
Example
let person = {
name: "Agustin",
age: 27,
};
Object.preventExtensions(person);
Object.isExtensible(person); // return false
person.surname = "Ramirez";
console.log(person.surname); // return undefined
person.name = "Maria";
console.log(person); // return { name: "Maria", age: 27 }
delete person.age;
console.log(person); // return { name: "Maria" }
seal
An object called by this method can not have any new properties being added or current properties deleted.
Example
let person = {
name: "Agustin",
age: 27,
};
Object.seal(person);
Object.isSealed(person); // return true
// In strict mode this will throw a `TypeError`
person.foo = "something";
console.log(person.foo); // return undefined
person.name = "Maria";
console.log(person); // return { name: "Maria", age: 27 }
delete person.age;
console.log(person); // return { name: "Maria", age: 27 }
Object.defineProperty(person, "name", {
get: () => "Juan",
}); // Throw TypeError
console.log(person); // return { name: "Maria", age: 27 }
freeze
An object called by this method can not have any further changes done to it.
Example
let person = {
name: "Agustin",
age: 27,
};
Object.freeze(person);
Object.isFrozen(person); // return true
person.name = "Maria";
console.log(person); // return { name: "Agustin", age: 27 }
shallow only
All of these methods only work on object properties shallowly, meaning that just work with the direct property references.
let person = {
name: "Agustin", // Prevented, Sealed and Frozen
age: 27, // Prevented, Sealed and Frozen
address: {
// Un-prevented, un-sealed and un-frozen
country: "Argentina", // Un-prevented, un-sealed and un-frozen
city: "Corrientes", // Un-prevented, un-sealed and un-frozen
},
};
Feature matrix
Feature | default | preventExtensions | seal | freeze |
---|---|---|---|---|
add new properties | ✓ | |||
remove existing properties | ✓ | ✓ | ||
change existing property values | ✓ | ✓ | ✓ |
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK