객체의 프로퍼티를 변경하는 방법에는 크게 2가지가 있다.

1. 객체의 프로퍼티를 직접 변경하는 방법

var player = {score: 1, name: 'Jeff'};
player.score = 2;

console.log(player); // {score: 2, name: 'Jeff'}
this.squares[i] = i;
this.squares[i] = 'Something';
console.log(this.squares[i]); /// [...,'Something',...]



2. 객체를 복제하여 변경하는 방법

var player = {score: 1, name: 'Jeff'};

var newPlayer = Object.assign({}, player, {score: 2});
// 또는
// var newPlayer = {...player, score: 2};


console.log(newPlayer, player)
// {score: 2, name: 'Jeff'}, {score: 1, name: 'Jeff'}


player = newPlayer;
this.squares[i] = i;
const squares = this.squares.slice(); // slice()를 이용해 쉽게 복제한다.
squares[i] = 'something';

console.log(squares, this.squares); // [...,'Something',...], [...,i의 값,...]

this.squares = sqaures;



Q. 1번 방법이 좋은거야 2번 방법이 좋은거야?

A. 대체로 2번 방법이 좋다

  • A.1 되돌리기 기능(Undo, Redo)을 구현하기 편하다.
  • A.2 객체의 차이를 알기 위해 요소를 순회하지 않아도 된다.
  • A.3 Vue.js나 React 같은 프레임워크가 HTML Elment의 리렌더링 필요성을 결정하기 수월하다.



부록

다른 방법?

  • 경우에 따라 더 편한 방법을 사용할 수 있다.
  • Array.structuredClone(), Lodash를 쓰기도 한다.
    • Array.structuredClone()은 브라우저 지원여부에 따라 결정하자.

By Value? By Reference?

The Difference Between Values and References in JavaScript

출처

React > 자습서 : React 시작하기

0개의 댓글