Last active
August 18, 2016 11:16
-
-
Save tomasr8/f72eb8200fcdc7764b54059f00883cc4 to your computer and use it in GitHub Desktop.
make object immutable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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