Skip to content

Instantly share code, notes, and snippets.

@ncaq
Last active April 29, 2020 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncaq/405d2d32f2bae906b3ca5b9c7554eb6d to your computer and use it in GitHub Desktop.
Save ncaq/405d2d32f2bae906b3ca5b9c7554eb6d to your computer and use it in GitHub Desktop.
JavaScriptの参照と浅いコピー
const stateA = { foo: "bar" };
const stateB = stateA;
stateB["hoge"] = "huga"; // stateAに対する破壊的変更
console.log("stateA: ", stateA); // stateAが更新されている
// コピーしたいならこうする
const correctStateA = { foo: "bar" };
const correctStateB = { ...correctStateA }; // 浅いコピー
correctStateB["hoge"] = "huga"; // correctStateAには影響が出ない
console.log("correctStateA: ", correctStateA);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment