Him*_*u P 3 javascript const object readonly immutability
如何在JavaScript中创建对象的只读/不可变版本,其属性无法更改?这也应该适用于任何子对象的属性等.
我所遇到的所有方法(Object.defineProperty,Object.freeze等)仅适用于对象的顶级属性,但不适用于子对象.
(可能的用例:在特定模块中创建/修改对象settings或configuration类型对象后,需要以不可变的形式将其公开给程序的其余模块.)
经过一番思考后,我想出了这个解决方案.适合我的需求,所以我想我会分享它的QnA风格.如果您找到它们,请建议任何改进/问题.
/**
* Make the the specified object (deeply) immutable or "read-only", so that none of its
* properties (or sub-properties) can be modified. The converted object is returned.
* @param {object} obj Input object
*/
makeImmutable: function makeImmutable (obj) {
if ((typeof obj === "object" && obj !== null) ||
(Array.isArray? Array.isArray(obj): obj instanceof Array) ||
(typeof obj === "function")) {
Object.freeze(obj);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
makeImmutable(obj[key]);
}
}
}
return obj;
}
Run Code Online (Sandbox Code Playgroud)
编辑:简化代码.现在也正确处理数组.