(ECMA Script) extend Object / Object Destructuring

soosoorim·2024년 5월 13일
0

extend Object

  • ECMAScript2015에서 프로퍼티 명과 변수명이 같을 경우 프로퍼티를 생략할 수 있도록 개선되었다.
    => 확장된 객체
function createPerson(name, age) {
  return {
    name,
    age
  };
}
const person = createPerson("James Dean", 30);
  • 객체 리터럴내 function을 정의하는 방법도 변경되었다.
    (기존)
function createPerson(name, age) {
  return {
    name,
    age,
    sayName: function() {
      console.log(this.name);
    }
  };
}
const person = createPerson("James Dean", 30);
person.sayName();
  • function() 키워드가 생략되면서 간결하게 메소드를 정의할 수 있다.
function createPerson(name, age) {
  return {
    ... 생략 ...
    sayName() {
      console.log(this.name);
    }
  };
}
const person = createPerson("James Dean", 30);
person.sayName();

Object Destructuring (객체, 배열 분해 할당)

  • 객체 리터럴이나 배열을 해체해 최소단위의 변수로 저장하는 방법
  • 기존에 객체리터럴이나 배열에서 데이터를 가져오는 방법

  • 기본 값 할당
  • 구조 분해시, 지정된 값이 없을 경우 undefined 로 지정되고, 이를 막기 위해 기본값을 할당할 수 있다.
    => 많이 씀!
  • 이름이 다른 변수에 할당하기
let node = {
  type: "Identifier",
  name: "foo"
};
let {type: localType, name: localName} = node;
console.log(localType, localName);
  • 구조 분해는 객체 리터럴 내의 이름이 같은 변수에 할당된다.
    다른 이름의 변수에 할당하고자 한다면, 아래와 같은 패턴으로 작성한다.
let {프로퍼티 명: 변수명, ...} = 객체 리터럴;
  • 배열의 구조 분해 할당
let colors = ["red", "green", "blue"];
let firstColor = "black";
let secondColor = "purple";
console.log(firstColor, secondColor);
[firstColor, secondColor] = colors;
console.log(firstColor, secondColor);

배열의 구조 분해시 객체의 분해처럼 괄호를 필요로하지 않는다.
구조 분해시 모든 배열의 개수를 맞출 필요가 없다. (단, 순서는 맞추어야 한다.)

  • 구조분해와 나머지 연산자를 이용해 배열 복사하기
  • 객체를 파라미터로 보낼 때 function의 파라미터로 구조 분해 할 수 있다.
function setAttribute(name, {url, method}) {
  console.log("name", name);
  console.log("url", url);
  console.log("method", method);
}
setAttribute("searchForm", {
  url: "http://localhost",
  method: "post"
});
  • 혹은 기본값을 이용해 아래처럼 사용할 수도 있다.
function setAttribute(name, {
  url = "http://localhost", 
  method = "post”
} = {}) {
  console.log("name", name);
  console.log("url", url);
  console.log("method", method);
}
setAttribute("searchForm");

0개의 댓글

관련 채용 정보