Deep Freezing a JS object
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 deepFreeze(obj) { | |
// Freeze properties first. Then freeze self. | |
const properties = Object.getOwnPropertyNames(obj); | |
// Iterate over the properties and get their values. | |
// Check if the value if not null and is an object itself. | |
// If so, recursively freeze it. | |
for (const property of properties) { | |
const value = obj[property]; | |
if (value && typeof value === "object") { | |
deepFreeze(value); | |
} | |
} | |
return Object.freeze(obj); | |
} | |
const spidey = deepFreeze({ | |
name: { | |
first: "Peter", | |
last: "Parker", | |
}, | |
alias: "Spiderman", | |
profession: "Photographer", | |
villains: ["Green Goblin", "Electro", "Venom", "Mysterio"], | |
}); | |
spidey.name.middle = "Benjamin"; | |
spidey.villains.push("Doc Ock"); | |
console.log(spidey); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment