“This is the 15th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

Frozen Beauty – Freezes JS objects

You may be surprised to see this title freezing JS objects, ah! Touch my knowledge blind spot again, so first to understand the JS object

JS object

Js objects are ordinary objects with key-value pairs, and their attributes are not quoted. The representation method is as follows. Objects have object attributes, and object methods have the same concept as ordinary objects

var obj = {
    name : "cxy",
    age : "18"
}
Copy the code

If obj.name = “juejin”, console.log(obj.name) can be printed to see the change effect. Let’s learn object.freeze ()

Object.freeze

Freeze () is the method used to freeze an object. Just pass the object we want to freeze as a parameter, and the object will be frozen

const iceObj = Object.freeze(obj)
Copy the code

So iceObj is the frozen object. What about freezing? Iceobj.age = “19”, and then print console.log(iceobj.age) to show that omygod is still 18. Object. IsFrozen, which returns a Boolean value

An object that cannot be frozen

Here’s another question: Can all objects be frozen? Nonono, object.freeze () The unfreezable nested Object is still the same Object, but has a son property that is itself an Object

var obj = {
    name : "cxy",
    age : "18"
    son : {
    name : "son",
    age : "1"
    }
}
Copy the code

Object.freeze() does not freeze all objects, but can also freeze arrays. You can define an array and freeze it. Freeze () object. Seal () object. Freeze () object

Object.seal

var obj = {
    name : "cxy",
    age : "18"
}
const iceObj = Object.seal(obj)
iceObj.name = "juejin"
delete iceObj.age
console.log(iceObj)
Copy the code

Freeze (), modify the name attribute, delete the age attribute, and print the name attribute successfully, but the age attribute is not deleted. Object. IsSealed, which returns a Boolean, and Object. PreventExtensions ().

Object.preventExtensions

Object. PreventExtensions is the ability to freeze the Object to add properties

var obj = {
    name : "cxy",
    age : "18"
}
const iceObj = Object.preventExtensions(obj)
iceObj.weight = "180"
console.log(iceObj)
Copy the code

The above code is to add the weight attribute to obj, but it does not appear after printing, indicating that the object attribute method is frozen.