-
9.5 값을 참조로 바꾸기
class Customer { #id; constructor(id) { this.#id = id; } get id() { return this.#id; } } class Order { #number; #customer; constructor(data) { this.#number = data.number; this.#customer = new Customer(data.customer); } get customer() { return this.#customer; } } const o = new Order({ number: 1, customer: 'a' });
- ex)
- 주문 목록엔 같은 고객이 요청한 주문이 여러 개 섞여 있을 수 있다,
- 이때 고객을 값으로도. 혹은 참조로도 다물 수 있다.
- 값으로 다룬다면 고객 데이터가 각 주문에 복사
- 참조로 다룬다면 여러 주문이 단 하나의 객체틀 참조
- 고객 데이터블 갱신할 일이 없다면 어느 방식이든 상관없
- 논리적으로 같은 데이터를 물리적으로 복제해 사용할 때 ( 값으로 다룰 때) 가장 크게 문제되는 상황은 그 데이터를 갱신해야 할 때
- 모든 복제본올 찾아서 빠심 없이 갱신해야 하며,하나라도 놓치면 데이터 일관성이 깨져버린다,
- 이런 상황이라면 복제된 데이터들올 모두 참조로 바꿔주는 게 좋다.
- 데이터가 하나면 갱신된 내용이 헤당 고객의 주문 모두에 곧바로 반영되기 때문이다.
-
class Customer { #id; constructor(id) { this.#id = id; } get id() { return this.#id; } } const findCustomer = (id) => _repositoryData.customers.get(id); class Order { #number; #customer; constructor(data) { this.#number = data.number; this.#customer = registerCustomer(data.customer); } get customer() { return findCustomer(this.#customer); } } const _repositoryData = { customers: new Map() }; const registerCustomer = (id) => { if (!_repositoryData.customers.has(id)) { _repositoryData.customers.set(id, new Customer(id)); } return id; }; const o = new Order({ number: 1, customer: 'a' }); console.log(o.customer.id);
- ex)