では「arguments の内部挙動」について、初心者向けに図解+実験つきで解説していきましょう💡
arguments の内部挙動とは?
まず、arguments とは?
関数の中で使える「すべての引数をまとめて扱える特別なオブジェクト」です。
function showArgs(a, b) {
console.log(arguments);
}
showArgs(10, 20);
// 👉 [10, 20]
JavaScript配列のように見えますが、実は配列ではない特別なオブジェクトです。Array.isArray(arguments) → false
内部的なしくみ
関数が「非 strict mode(通常)」か「strict mode(厳格モード)」かで、arguments の動きが大きく変わります。
非 strict mode の場合(デフォルト)
引数と arguments がリンクしている!
function test(a) {
console.log(arguments[0]); // 10
a = 99;
console.log(arguments[0]); // 99 ← a と連動!
}
test(10);
JavaScript🧠 ポイント:
arguments[0]とaは同じ値を共有している。- どちらかを変えると、もう一方も変わる。
🧩 イメージ図:
a ─┐
│ 同じ実体を指している
arguments[0] ┘
strict mode の場合
"use strict";
function test(a) {
console.log(arguments[0]); // 10
a = 99;
console.log(arguments[0]); // 10 ← 連動しない!
}
test(10);
JavaScript🧠 ポイント:
aとarguments[0]は完全に別の変数。- 一方を変えても、もう一方は変わらない。
- これは安全性・可読性を高めるため。
🌍 実際にブラウザで比較してみよう!
以下を HTML ファイルに保存して実行してみてください👇
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>arguments と strict mode の比較</title>
</head>
<body>
<h2>arguments と strict mode の比較</h2>
<button onclick="runNormal()">通常モード</button>
<button onclick="runStrict()">strict モード</button>
<pre id="output"></pre>
<script>
function log(msg) {
document.getElementById("output").textContent += msg + "\n";
}
// 通常モード(非 strict)
function runNormal() {
document.getElementById("output").textContent = "【非 strict モード】\n";
function test(a) {
log("最初 a = " + a);
log("最初 arguments[0] = " + arguments[0]);
a = 99;
log("変更後 a = " + a);
log("変更後 arguments[0] = " + arguments[0]);
}
test(10);
}
// strict モード
function runStrict() {
document.getElementById("output").textContent = "【strict モード】\n";
"use strict";
function test(a) {
log("最初 a = " + a);
log("最初 arguments[0] = " + arguments[0]);
a = 99;
log("変更後 a = " + a);
log("変更後 arguments[0] = " + arguments[0]);
}
test(10);
}
</script>
</body>
</html>
JavaScript🔹 ボタンを押すと、それぞれの挙動をリアルタイムに比較できます。
🔹 「非 strict」ではリンク、「strict」では独立しているのが一目瞭然!
まとめ
| 比較項目 | 非 strict mode | strict mode |
|---|---|---|
引数と arguments のリンク | 🔗 あり | ❌ なし |
| パフォーマンス | やや低い(同期処理あり) | 高い(独立) |
| 現代的な書き方 | 非推奨 | ✅ 推奨 |
ES6 の ...args | 常に安全 | ✅ 安全 |
See the Pen Untitled by MONO365 -Color your days- (@monoqlo365) on CodePen.
