简体   繁体   中英

Nested objects in javascript how to freeze it?

I am trying to freeze javascript nested object. As I am new to JS I am facing difficulty to freeze the nested objects.

const obj = { prop: { innerProp: 1 } };
obj.prop.innerProp = 5;
console.log(obj.prop.innerProp); // 5

Is it possible do freeze nested objects?

You can use the following example to freeze nested objects

function deepFreeze (o) {
Object.freeze(o);
if (o === undefined) {
return o;
}

Object.getOwnPropertyNames(o).forEach(function (prop) {
if (o[prop] !== null
&& (typeof o[prop] === "object" || typeof o[prop] === "function")
&& !Object.isFrozen(o[prop])) {
  deepFreeze(o[prop]);
}
});

return o;
};

You can use Immutable.js which is a library for working with immutable values. Moreover, in terms of performance, especially if you constantly make use of immutable variables in project, Immutable.js is a great choice, since deepFreeze more costly in terms of performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM