Start with strings, numbers and booleans
Copy let age = 100;
let age2 = age;
console.log(age, age2); //100, 100
age = 200;
console.log(age, age2); //200, 100
age2์ age๋ฅผ ํ ๋นํ๊ณ age๋ฅผ ๋ฐ๊ฟ์ง๋ง age2์ ๊ฐ์ ๋ณํ์ง ์๋๋ค.
์ด๊ฒ์ primitive
์ด๊ธฐ ๋๋ฌธ์ด๋ค.
Reference - array
Copy // Let's say we have an array
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
// and we want to make a copy of it.
const team = players;
console.log(players, team); // ['Wes', 'Sarah', 'Ryan', 'Poppy'] x2
// You might think we can just do something like this:
team[3] = 'Lux';
console.log(players, team); // ['Wes', 'Sarah', 'Ryan', 'Lux'] x2
๋๋ team์ ๋ณ๊ฒฝํ์ง๋ง, players๋ ์ํฅ์ ๋ฐ๋๋ค. ๋ด๊ฐ ์ค๋ฆฌ์ง๋์ด๋ ๋ค๋ฅธ array๋ฅผ ๋ณ๊ฒฝํ๋ฉด ๊ทธ๊ฒ์ reference๋ก ๋๋์ ๊ฐ๋ ค๊ณ ํ๋ค.
Array copy
Copy const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
// copy ๋ฐฉ๋ฒ 1
const team1 = players.slice();
// copy ๋ฐฉ๋ฒ 2
const team2 = [].concat(players);
team2[2] = 'Lux';
// copy ๋ฐฉ๋ฒ 3 - es6 spread
const team3 = [...players];
// copy ๋ฐฉ๋ฒ 4
const team4 = Array.from(players);
console.log(team2) // ['Wes', 'Sarah', 'Ryan', 'Lux'];
console.log(players) // ['Wes', 'Sarah', 'Ryan', 'Poppy'];
referenceํ๊ณ ์ถ์ง์๊ณ copy๊ฐ ๋ชฉํ๋ผ๋ฉด slice, concat, spread, Array.from ์ด 4๊ฐ์ง๋ฅผ ์ด์ฉํ์.
With Objects
Copy const person = {
name: 'Wes Bos',
age: 80
};
const captain = person;
captain.number = 99;
console.log(person) // {name: 'Wes Bos',age: 80, number: 99}
Object copy
Copy const person = {
name: 'Wes Bos',
age: 80
};
// copy ๋ฐฉ๋ฒ 1 - 3๋ฒ์งธ ์ธ์๋ ์๋ก ์ถ๊ฐ, ์์ ํ key, value์ด๋ค.
const cap1 = Object.assign({}, person, { number: 99, age: 12 });
// copy ๋ฐฉ๋ฒ 2
const cap2 = {...person};
Object - one level deep
Copy const wes = {
name: 'Wes',
age: 100,
social: {
twitter: '@wesbos',
facebook: 'wesbos.developer'
}
}
const dev = {...wes};
dev.social.twitter = '@coolman';
console.log(dev.social); // {twitter: "@coolman", facebook: "wesbos.developer"}
console.log(wes.social); // {twitter: "@coolman", facebook: "wesbos.developer"}
one level deep์ ์๋ ๋ด์ฉ์ reference๋ผ wes.social๋ฅผ ์ฐธ์กฐํ๋ค. wes๋ ์ด ๋ด์ฉ์ shit์ด๋ผ ํํํ๋ค.
์ด๋ฐ์์copy๋ ์ค์ง one level deep๋ง ๊ฐ๋ฅํ๋ค.
๋ชจ๋ level deep์ ํ๊ณ ์ ํ ๊ฒฝ์ฐ ๋จผ์ ์ค์ค๋ก์๊ฒ ๋ฌผ์ด์ผ ํ๋ค. ์ด๊ฒ ์ ๋ง ํ์ํ๊ฐ?
ํ์ง๋ง ์ ๋ง every level deep์ด ํ์ํ๋ค๋ฉด? (์ถ์ฒx)
Copy const wes = {
name: 'Wes',
age: 100,
social: {
twitter: '@wesbos',
facebook: 'wesbos.developer'
}
}
const dev2 = JSON.parse(JSON.stringify(wes));
dev2.social.twitter = '@coolman';
// ์ค๋ฆฌ์ง๋ ๊ฐ์ฒด์๋ ํฐ์น๊ฐ ์๋ค.
console.log(wes.social);// {twitter: "@wesbos", facebook: "wesbos.developer"}
/*
* JSON์ string์ ๋ฐํํ๋ค.
* JSON.stringify(wes)
* ํ์ง๋ง JSON.parse์ ์ฌ์ฉํ์ฌ ๊ฐ์ฒด๋ฅผ ๋ฐํํ์๋ค.
*/
์ด๋ฅผ .. poor man's deep clone
์ด๋ผ ๋ถ๋ฆฐ๋ค.'ใ
'... ํ