2277

人生お勉強

理解負債003

Object.freezeに遭遇。

const CONFIG  = Object.freeze({
  VERSION:'1.4.7',
  TIME_ZONE:'Asia/Tokyo',
  URL:'https://example.com',
  num:3
})

そのままオブジェクトを凍結する。

constは再代入を防ぎ、Oject freezeは中身の書き換え、追加を防ぐと。

//constのみ
function check(){
  //1.constのみ
  const a = {value:1};
  a.value = 999;
  console.log(`1.constのみ -> a.value : ${a.value}`)
  //これは書き換わってしまう!

  //2.const + freeze
  const b = Object.freeze({value:1});
  b.value = 999;
  console.log(`2.const + freeze -> b.value : ${b.value}`)
  //これは書き換わらない!

  //3.ネストは守らない様子
  const c = Object.freeze({ nested: { value:1 } });
  c.nested.value = 2;
  console.log(`3.ネスト: ${c.nested.value}`)
  //これは書き換わる!!
}

結果

constはオブジェクトを定義して、それ自体の再定義は出来ないが、そのオブジェクトのプロパティの変更はできる。

Object.freezeはこれも防ぐことはできるが、ネストされたオブジェクトプロパティの変更は防ぐことは出来ない。