[JavaScript] Protecting Data Integrity: Completely Restricting Changes with Static Methods

目次

Overview

In JavaScript, even objects defined with const can have their internal properties modified freely. However, in scenarios such as managing application settings or system-wide constants, allowing any changes during runtime can lead to critical bugs. This article explains how to implement Object.freeze, a method that “freezes” an object to make the addition, deletion, or modification of its properties physically impossible.

Specifications (Input/Output)

MethodPurposeReturn Value
Object.freeze()Freezes the object. Prevents modification, deletion of existing properties, and addition of new ones.The frozen object itself.
Object.isFrozen()Determines if the specified object is already frozen.Returns true if frozen, false otherwise.

Basic Usage

Once Object.freeze is executed, the target object becomes read-only. In non-strict mode, attempts to modify it are simply ignored. However, in a modern strict mode environment, any attempt to change a property will immediately trigger a TypeError, facilitating early bug detection and ensuring that the data structure remains immutable throughout its lifecycle.

Full Code Implementation (HTML / JAVASCRIPT)

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cloud Environment Guard</title>
</head>
<body>
    <div id="config-manager">
        <h2>Environment Configuration Manager</h2>
        <div id="log-output"></div>
        <hr>
        <button id="update-attempt">Attempt to Modify Settings</button>
        <button id="check-status">Check Freeze Status</button>
    </div>
    <script type="module" src="main.js"></script>
</body>
</html>

JavaScript

'use strict';

/**
 * System environment configuration object
 * Scenario: Managing cloud server connection settings
 */
const cloudConfig = {
  endpoint: "https://api.v3.internal.service",
  retryLimit: 5,
  adminUser: "mori"
};

// Freezing the configuration object to prevent any changes
Object.freeze(cloudConfig);

const logOutput = document.getElementById('log-output');

/**
 * Renders processing results to the screen
 * @param {string} message 
 */
const printLog = (message) => {
  const p = document.createElement('p');
  p.textContent = message;
  logOutput.appendChild(p);
};

// 1. Behavior when attempting to modify the object
document.getElementById('update-attempt').addEventListener('click', () => {
  try {
    printLog("Attempting to change values...");
    // Since it is frozen, these operations will throw an error in strict mode
    cloudConfig.retryLimit = 10;
    cloudConfig.newOption = "enabled";
  } catch (error) {
    printLog(`Error detected: ${error.message}`);
    console.error("Modification blocked by Object.freeze:", error);
  }
});

// 2. Using the status verification method
document.getElementById('check-status').addEventListener('click', () => {
  const isFrozen = Object.isFrozen(cloudConfig);
  printLog(`Current freeze status of this object: ${isFrozen}`);
});

printLog(`Initial Administrator: ${cloudConfig.adminUser}`);

Customization Points

Beyond standard configuration objects, this method should be applied to objects used as “Enums” that hold a fixed set of options. In large-scale applications, it is effective to call Object.freeze as a guard clause immediately after the data initialization is complete. This ensures that no unintended side effects can alter the core data as it is passed between different modules or functions.

Important Considerations

It is vital to understand that Object.freeze performs a “Shallow Freeze.” If an object property contains another nested object, the contents of that nested child object are not automatically protected. Furthermore, JavaScript does not provide a built-in way to “unfreeze” an object once the method has been applied. If you need a version of the data that can be changed, you must create a new variable by copying the original object. Finally, because operations on frozen objects fail silently in environments where strict mode is disabled, you should always use 'use strict'; to ensure that unauthorized modifications are properly surfaced as errors.

Advanced Applications

Object.freeze can also be applied to arrays to prevent destructive operations. This effectively blocks methods like push, pop, or direct index assignment from altering the list.

'use strict';

/**
 * Immutable list of access levels
 */
const securityLevels = [1, 5, 10];
Object.freeze(securityLevels);

try {
  // Attempting to push a new element will fail because the array is frozen
  securityLevels.push(20);
} catch (e) {
  console.log("Array updates are restricted.");
}

console.log(securityLevels); // Output: [1, 5, 10]

Summary

Object.freeze plays a critical role in enhancing the robustness of data within JavaScript applications. It allows developers to enforce language-level constraints that prevent property tampering and destructive changes, going far beyond what simple const declarations can offer. This technique is highly recommended when developing shared libraries or defining common constants in team-based projects, as it explicitly protects data that must remain unchanged. By combining this with state checks using Object.isFrozen, you can implement a design that reliably maintains data integrity and prevents difficult-to-track bugs caused by unexpected mutations.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次