Skip to content

Instantly share code, notes, and snippets.

@tomasr8
Last active August 18, 2016 11:16
Show Gist options
  • Save tomasr8/f72eb8200fcdc7764b54059f00883cc4 to your computer and use it in GitHub Desktop.
Save tomasr8/f72eb8200fcdc7764b54059f00883cc4 to your computer and use it in GitHub Desktop.
make object immutable
"use strict";
function freeze(obj) {
if(typeof obj !== "object") {
return;
}
Object.freeze(obj);
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
freeze(obj[prop]);
}
}
}
let obj = { a: 5, nested: { b: 6, arr: [1, 2] } };
freeze(obj);
//obj.a = 7; // --> TypeError
//obj.nested = null; // --> TypeError
//obj.nested.b = -5; // --> TypeError
//obj.c = "new prop"; // --> TypeError
obj.nested.arr.push(13); // --> TypeError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment