解説
プログラムで出てくる値や配列、オブジェクトなどのうち、メモリーの内容が変更可能なものを「ミュータブル」、変更不能なものを「イミュータブル」と言います。
文脈によってはミュータブルオブジェクト、イミュータブルオブジェクトを指すこともあります。この場合は、オブジェクト自身の状態(プロパティ)が変更可能か、変更不能かを意味します。
サンプル
「ミュータブルとイミュータブル」のサンプルです。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>「ミュータブルとイミュータブル」のサンプル</title>
<style> #output { font-size: 24px; line-height: 1.5; } </style>
</head>
<body>
<pre id="output"></pre>
<script type="module">
// 出力用の関数
const print = function() {
const el = document.querySelector('#output');
el.textContent += [...arguments].map(x =>
typeof(x) === 'string' ? x :
JSON.stringify(x)).join(' ') + '\n';
};
// 文字列(イミュータブル)
try {
let text = 'abcdefg';
print('text 1 :', text);
text[1] = 'B';
print('text 2 :', text);
} catch(e) {
print(e.message);
}
print('--');
// オブジェクト(ミュータブル)
let obj = {a: 1, b: 2};
print('object 1 :', obj);
obj.a = 111;
print('object 2 :', obj);
// オブジェクト(イミュータブル)
try {
Object.freeze(obj);
obj.a = 999;
print('object 3 freeze :', obj);
} catch(e) {
print(e.message);
}
</script>
</body>
</html>
text 1 : abcdefg
Cannot assign to read only property '1' of string 'abcdefg'
--
object 1 : {"a":1,"b":2}
object 2 : {"a":111,"b":2}
Cannot assign to read only property 'a' of object '#<Object>'
フィードバックお待ちしております!
ご感想、解説してほしい用語、解説内容のアドバイスなどございましたら、FacebookやX(旧Twitter)などでお気軽に編集部までお寄せください。よろしくお願いいたします。
