4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

constの再代入禁止とオブジェクトの凍結

Posted at

変数宣言時にconstを使えば変数への再代入を防ぐことができます。

sample
const con = 1000;
con = 500;

// エラー発生 Uncaught TypeError: Assignment to constant variable.

constであってもオブジェクトのプロパティの変更や追加削除を防ぐことはできません。

const con = {
  prop1: 'p1',
  prop2: 'p2',
};

con.prop1 = 'p3';
con.prop3 = 'p3';
console.log(con); // {prop1: "p3", prop2: "p2", prop3: "p3"}

Object.freezeを使うことでプロパティに変更や追加を防ぐことができます。

const con = {
  prop1: 'p1',
  prop2: 'p2',
};

// オブジェクトを凍結
Object.freeze(con);

con.prop1 = 'p3';
con.prop3 = 'p3';
console.log(con); // {prop1: "p1", prop2: "p2"}

Object.freezeの凍結は対象のオブジェクトだけです。より深いオブジェクトは凍結されないので注意。

const con = {
  prop1: 'p1',
  prop2: 'p2',
  deep: {
    prop4: 'p4'
  }
};
Object.freeze(con);

con.deep.prop4 = 'p5';
console.log(con); // {prop1: "p1", prop2: "p2", deep: { prop4: "p5"}}
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?