JavaScript | arguments と strict mode の関係

JavaScript JavaScript
スポンサーリンク

では、「通常モード vs strict モード」の arguments の違いをブラウザで実際に比較できるサンプルを用意します。
ボタンを押すと結果が表示され、2つの挙動の違いが一目でわかります。


💻 実行比較サンプル(HTML+JavaScript)

保存名:arguments_strict_compare.html

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>arguments と strict mode の比較</title>
<style>
body { font-family: "Segoe UI", sans-serif; margin: 30px; background: #f9f9f9; }
h2 { margin-top: 30px; }
button { margin: 10px 0; padding: 8px 16px; border: none; border-radius: 6px; cursor: pointer; }
button.normal { background: #4CAF50; color: white; }
button.strict { background: #2196F3; color: white; }
pre { background: #fff; padding: 10px; border-radius: 6px; box-shadow: 0 0 5px rgba(0,0,0,0.1); }
</style>
</head>
<body>
<h1>🧩 arguments と strict mode の比較</h1>
<p>「通常モード」と「strict mode」で <code>arguments</code> の挙動がどう違うか確認できます。</p>

<h2>通常モード(非 strict)</h2>
<button class="normal" onclick="runNormal()">実行する</button>
<pre id="normalResult"></pre>

<h2>strict mode(厳格モード)</h2>
<button class="strict" onclick="runStrict()">実行する</button>
<pre id="strictResult"></pre>

<script>
// ===== 通常モード =====
function demoNormal(a, b) {
  let log = [];
  log.push(`初期値: a=${a}, b=${b}`);
  log.push(`初期 arguments: [${arguments[0]}, ${arguments[1]}]`);

  a = 99;
  log.push(`a=99 に変更 → arguments[0] は ${arguments[0]}`);

  arguments[1] = 77;
  log.push(`arguments[1]=77 に変更 → b は ${b}`);

  return log.join("\n");
}

function runNormal() {
  const result = demoNormal(1, 2);
  document.getElementById("normalResult").textContent = result;
}

// ===== strict mode =====
function demoStrict(a, b) {
  'use strict';
  let log = [];
  log.push(`初期値: a=${a}, b=${b}`);
  log.push(`初期 arguments: [${arguments[0]}, ${arguments[1]}]`);

  a = 99;
  log.push(`a=99 に変更 → arguments[0] は ${arguments[0]}`);

  arguments[1] = 77;
  log.push(`arguments[1]=77 に変更 → b は ${b}`);

  return log.join("\n");
}

function runStrict() {
  const result = demoStrict(1, 2);
  document.getElementById("strictResult").textContent = result;
}
</script>
</body>
</html>
HTML

実行するとこうなります

✅ 通常モード

初期値: a=1, b=2
初期 arguments: [1, 2]
a=99 に変更 → arguments[0] は 99
arguments[1]=77 に変更 → b は 77

🚫 strict mode

初期値: a=1, b=2
初期 arguments: [1, 2]
a=99 に変更 → arguments[0] は 1
arguments[1]=77 に変更 → b は 2

💡 観察ポイント

  • 通常モードでは aarguments[0] が「リンク」しており、両方変わる。
  • strict mode では「別の変数」として扱われ、同期しない。

See the Pen Normal Mode vs Strict Mode by MONO365 -Color your days- (@monoqlo365) on CodePen.

タイトルとURLをコピーしました