The use of js frozen object Object.freeze() method

We all know that const defines the basic data type, and this value cannot be modified. So if we define an object using const, can we modify the object?

const a = 5
// a = 10  // TypeError: Assignment to constant variable.

const obj = {
    name: '张三'
}
obj.name = '李四'
console.log(obj)    // {name: "李四"}

The answer is yes. So what should we do if we want to define an object that cannot be modified?
Then you need to use Object.freeze().
Its function is to freeze an object. The frozen object has the following characteristics:

  • Cannot add new properties
  • Cannot delete existing attributes
  • Cannot modify the value of existing attributes
  • Cannot modify prototype
  • The enumerability, configurability, and writability of existing properties cannot be modified.
Basic usage
var obj = {
    name: '张三',
    age: 18,
    address: '上海市'
}
obj.__proto__.habit = '运动'
 
// 冻结对象
Object.freeze(obj)
 
// 不能添加新属性
obj.sex = '男'
console.log(obj)    // {name: "张三", age: 18, address: "上海市"}
 
// 不能删除原有属性
delete obj.age
console.log(obj)    // {name: "张三", age: 18, address: "上海市"}
 
// 不能修改已有属性的值
obj.name = '李四'
console.log(obj)    // {name: "张三", age: 18, address: "上海市"}
 
// 不能修改原型
obj.__proto__ = '随便什么值'
console.log(obj.__proto__)  // {habit: "运动", constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, …}
 
// 不能修改已有属性的可枚举性、可配置性、可写性
Object.defineProperty(obj,'address',{ // TypeError: Cannot redefine property: address
    enumerable: false,// 表示是否可以枚举。直接在对象上定义的属性,基本默认true
    configurable: false,// 表示能否通过delete删除属性,能否修改属性的特性
    writable: true// 表示能否修改属性的值。直接在对象上定义的属性,基本默认true
})

One thing to note here is that the return value of Object.freeze() is the frozen object, which is completely equal to the incoming object, so we generally do not need to receive the return value. We have frozen the object above, so can we freeze the array?

freeze array
var arr = [1,2,3,4,5]
Object.freeze(arr)
arr[0]='新值'
console.log(arr)    // [1, 2, 3, 4, 5]

In fact, it is easy to understand that the essence of an array is an object, but the key of the object is a subscript, so it can also be frozen. If there are still objects in my object, will the freeze still be effective?

shallow freeze
var obj = {
    name: '张三',
    info: {
        a: 1,
        b: 2
    }
}
Object.freeze(obj)

obj.name = '李四'
console.log(obj)    // {info: {a: 1, b: 2},name: "张三"}

obj.info.a = 66
console.log(obj.info)   // {a: 66, b: 2}

You can see that if there are still objects in the object, Object.freeze() fails. Object.freeze() only supports shallow freezing. Below we encapsulate a deep freezing function, which can be used directly in the future.

deep freeze
var obj = {
    name: '张三',
    info: {
        a: 1,
        b: 2
    }
}

function deepFreeze(obj) {
    // 获取所有属性
    var propNames = Object.getOwnPropertyNames(obj)
 
    // 遍历
    propNames.forEach(item => {
        var prop = obj[item]
        // 如果某个属性的属性值是对象,则递归调用
        if (prop instanceof Object && prop !== null) {
            deepFreeze(prop)
        }
    })

    // 冻结自身
    return Object.freeze(obj)
}

deepFreeze(obj)

obj.name = '李四'
console.log(obj)    // {name: "张三", info: {…}}

obj.info.a = 100
console.log(obj.info)   // {a: 1, b: 2}
Application scenarios

Object.freeze() can improve performance. If you have an object with a lot of content in it, and it is all static data, and you are sure not to modify it, you can actually freeze it with Object.freeze(), like this It can greatly improve performance, and the effect of improvement increases with the increase in data volume. When is it usually used? For big data that is purely for display, you can use Object.freeze to improve performance.

Using Object.freeze in Vue

In vue projects, there are usually many variables in data initialization. If you don't want to use it later, you can use Object.freeze(). This can avoid doing some useless operations when Vue is initialized, thereby improving performance.

data(){
    return{
        list:Object.freeze({'我不需要改变'})
    }
}

Guess you like

Origin blog.csdn.net/shanghai597/article/details/131982866