/ FRONTEND

클린코드 자바스크립트 6-1 객체 다루기(Object Destructuring, Object.freeze)

Clean Code JS 강좌는 여러 절로 구성되어 있습니다.

객체 다루기 😎

Object Destructuring👍

function Person(name, age, location) {
  this.name = name;
  this.age = age;
  this.location = location;
}

const john = new Perosn("john", 30, "Korea");

function Person({ name, age, location }) {
  this.name = name;
  this.age = age ?? 30;
  this.location = location ?? "korea";
}

const john = new Perosn({
  name: "john",
  age: 30,
  location: "Korea",
});

// name이 필수일 경우
// 명시적 표현 가능
function Person(name, { age, location }) {
  this.name = name;
  this.age = age ?? 30;
  this.location = location ?? "korea";
}

const johnOptions = {
  age: 30,
  location: "Korea",
};
const john = new Perosn("poco", johnOptions);
const orders = ["First", "Second", "Third"];

const st = orders[0];
const rd = orders[2];

console.log(st);
console.log(rd);

const [first, , third] = orders;

console.log(first);
console.log(third);

// 생각보다 이런 경우가 많음
const { 0: st2, 2: rd2 } = orders;
console.log(st2);
console.log(rd2);
  • Ex) React 경우
function Welcome(props) {
  return <h1>Hello {props.name} </h1>;
}

// 객체 구조 분해 할당
function Welcome2({ name }) {
  return <h1>Hello {name} </h1>;
}

Object.freeze👍

const STATUS = Object.freeze({
  PENDING: "PENDING",
  SUCCESS: "SUCCESS",
  FAIL: "FAIL",
});

STATUS.NEW_PROP = "P2";
console.log(STATUS); // PENDING: "PENDING",SUCCESS: "SUCCESS",FAIL: "FAIL"

Object.isFrozen(STATUS); // true
Object.isFrozen(STATUS.PENDING); // true
Object.isFrozen(STATUS.FAIL); // true

shallow copy vs deep copy

  • 깊은 복사에는 관여를 못한다.
const STATUS = Object.freeze({
  PENDING: "PENDING",
  SUCCESS: "SUCCESS",
  FAIL: "FAIL",
  OPTION: {
    GREEN: "GREEN",
    RED: "RED",
  },
});
STATUS.OPTIONS.GREEN = "G";
STATUS.OPTIONS.YELLOW = "Y";

console.log(STATUS.OPTIONS); //     GREEN: "GREEN", RED: "RED", YELLOW:"Y"
Object.isFrozen(STATUS.OPTIONS.GREEN); // false Deep Freezing 이 되지 않는다.

중첩된 Freezing 해결 방법🌼

  1. 대중적인 유틸 라이브러리(lodash)
  2. 직접 유틸 함수 생성
  3. stackoverflow
  4. TypeScript
function deepFreeze(targetObj) {
  // 1. 객체를 순회
  // 2. 값이 객체인지 확인
  // 3. 객체이면 재쉬
  // 4. 그렇지 않으면 Object.freeze
  Object.keys(targetObj).forEach(key => {
    if(/*객체가 맞다면*/) {
      deepFreeze();
    }
  })
  return Object.freeze(targetObj);
}