JavaScript Object Protection

Object protection techniques like Object.freeze(), Object.seal(), and Object.preventExtensions() help lock down objects, preventing accidental or malicious property modifications.

Key Topics

freeze(), seal(), preventExtensions()

Object.freeze(obj) makes the entire object immutable. Object.seal(obj) prevents adding or removing properties but allows modifying existing ones. Object.preventExtensions(obj) only prevents adding new properties.

let config = { appName: "MyApp", version: "1.0" };
Object.seal(config);
config.version = "1.1"; // Allowed
config.newProp = "Test"; // Ignored in sealed objects
console.log(config);

Output

> { appName: "MyApp", version: "1.1" }

Explanation: We updated version but adding a new property newProp is disallowed since the object is sealed.

Property Descriptors

For fine-grained control, define or modify property descriptors (e.g., writable, configurable) on individual properties rather than locking the entire object.

Read-Only & Sensitive Data

Freezing or sealing objects containing sensitive data ensures they remain stable. This approach is helpful in larger applications where shared state must not be overwritten accidentally.

JavaScript Usage in DOM

Below is a complete DOM example demonstrating object protection in a UI context.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Object Protection in DOM</title>
</head>
<body>
    <h1>Object Protection Demo</h1>
    <button onclick="freezeConfig()">Freeze Config</button>
    <button onclick="modifyConfig()">Try Modify</button>
    <p id="status"></p>

    <script>
        let appConfig = {
            name: "MySecureApp",
            version: "1.0"
        };

        function freezeConfig() {
            Object.freeze(appConfig);
            document.getElementById("status").textContent = "Config object frozen. No modifications allowed.";
        }

        function modifyConfig() {
            appConfig.version = "2.0";
            appConfig.newProp = "abc";
            document.getElementById("status").textContent = "After modification attempt: " + JSON.stringify(appConfig);
        }
    </script>
</body>
</html>

Output

> After modification attempt: {"name":"MySecureApp","version":"1.0"}

Explanation: Once frozen, appConfig remains unchanged even when we attempt to modify properties or add new ones.

Key Takeaways

  • freeze()/seal()/preventExtensions(): Provide different levels of object lockdown.
  • Property Descriptors: Fine-tune restrictions on individual properties.
  • Read-Only Data: Protect sensitive or critical config in apps.
  • DOM Integration: Freeze or seal objects to keep UI state consistent.