Last active
April 29, 2020 14:13
JavaScriptの参照と浅いコピー
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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