js implementation object cannot be changed

Variables can use const to keep the variables unchanged. But const for objects only keeps the link between the object name and value unchanged. It is possible to change the attribute value of the object.

But how to ensure that the properties of the object do not change.

There is a function Object.freeze() in js that can ensure that the properties of the object do not change, but if the properties in the object are still objects, it will be out of reach. Need help from deep copy at this time

	function deepFreeze(obj) {
    
    
    var propNames = Object.getOwnPropertyNames(obj);
    propNames.forEach(function(name) {
    
    
        var prop = obj[name];
        if (typeof prop == 'object' && prop !== null) {
    
    
            deepFreeze(prop);
        }
    });
    return Object.freeze(obj);
}

Also wondering how Object.freeze() is implemented?

I think it should be Object.property(obj, key, {}) to set writable: false to set unchangeable. Then expand Object.seal(obj) to make the object unexpandable.

Guess you like

Origin blog.csdn.net/qq_42535651/article/details/104379106