모던 자바스크립트 핵심가이드

카오·2021년 8월 31일
0
post-thumbnail

책을 보며 자주 언급되는 내용을 제외한 체크하면 좋을 부분을 정리

화살표 함수를 피해야 하는 경우

화살표 함수에서 this를 주의해서 사용해야 하는 경우.

이벤트 핸들러 사용 시

const button = document.querySelector("btn");
button.addEventListener("click", () => {
  // 여기서 this는 window
  this.classList.toggle("on");
});

객체에 함수사용 시

const person1 = {
  age: 10,
  grow: function () {
    this.age++;
    console.log(ths.age);
  }
};

person1.grow();

const person2 = {
  age: 10,
  grow: () => {
    // 오류 여기서 this는 윈도우
    this.age++;
    console.log(this.age);
  }
};

person2.grow();

함수 안에서 arguments정보 접근 시 레퍼런스 에러 발생

const shoWinner = () => {
  const winner = arguments[0];
  console.log(`${winner} was the winner`);
  // ReferenceError : arguments is not defined
};

화살표함수에서는 ...args와 같은 Rest파라미터 이용

const shoWinner = (...args) => {
  const winner = args[0];
  console.log(`${winner} was the winner`);
};

함수에 인수 기본값

ES6이전

기본값 설정 안됨( 함수 안에서 인수값 체크 필요)

function getLocation(city, country, continent) {
  if (typeof country == "undefined") {
  }

  if (typeof city == "undefined") {
  }
}

인자의 기본값을 중간에 넣으려면 호출 시 해당 인자의 순서에 undefined를 넣어줘야 함.

function getLocation(city, country, continent) {
  if (typeof country == "undefined") {
  }

  if (typeof city == "undefined") {
  }
}

getLocation(undefined, "Paris");

ES6후
기본값 설정 가능

function getLocation(city, country = "Paris", continent = "France") {
  console.log(city, country, continent);
}

getLocation("Seoul");

특정 매개변수 전달을 건너띄려면 undefined를 이용

function getLocation(city, country = "Paris", continent = "France") {
  console.log(city, country, continent);
}

getLocation("Seoul", undefined, "AAA");

디스트럭처링(구조분해할당)을 이용하면 더 세련되게 처리가 가능

function getLocation({ city, country = "Paris", continent = "France" } = {}) {
  console.log(city, country, continent);
}

getLocation({ city: "Seoul" });
getLocation();

이때 인수객체의 기본값을 빈 객체로 설정하지 않으면 다음과 같은 디스트럭처링 에러가 발생하니 주의

    Connot destructure property 'total' of 'undefined' or 'null';

디스트럭처링( 구조분해할당 )

배열의 값 또는 객체의 속성을 풀어서 별개의 변수로 쓸 수 있게 해주는 자바스크립트 표현식

const person = {
  first: "Alberto",
  last: "Montalesi"
};

const { first, last } = person;

중첩된 객체 형태의 데이터도 동일한 방식으로 적용가능

const person = {
  first: "Alberto",
  last: "Montalesi",
  links: {
    social: {
      facebook: "https://www.facebook.com/alberto.montalesi"
    },
    website: "https://albertmontalesi.github.io/"
  }
};

const { facebook } = person.links.social;

아래와 같이 사용해 변수의 이름을 변경도 가능

 cosnt {facebook:fb} = person.links.social;
 console.log(fb);
 console.log(facebook) // ReferenceError : facebook is not defined

위 코드는 const {facebook:fb} person.links.social객체의 속성 facebook을 대상으로 지정하고 const 변수를 fb라고 명명한다.

다음과 같이 기본값 전달도 가능

 cosnt {facebook:fb = "https://www.facebook.com"} = person.links.social;

디스트럭처링을 이용한 변수 교체

임시변수를 이용하지 않고 깔끔하게 변경가능

let hungry = "yes";
let full = "no";
[hungry, full] = [full, hungry];
console.log(hungry, full);

배열메서드

Array.of

전달받은 모든 인수를 배열로 생성.

const digits = Array.of(1, 2, 3, 4, 5);
console.log(digits);

스프레드 연산자와 레스트 매개변수

스프레드 문법을 사용하면 0개 이상의 인수(함수 호출용) 또는 원소(배열 리터럴용)가 예상되는 위치에서 배열 표현식 또는 문자열과 같은 이터러블 항목을 확장하거나 0개 이상의 키/값 쌍(객체 리터럴용)이 예상되는 위치에서 객체 표현식을 확장할 수 있다.

const veggie = ["tomato", "cucumber", "beans"];
const meat = ["pork", "beef", "chicken"];
const menu = [...veggie, "pasta", ...meat];
console.log(menu);

배열의 복사

배열의 복사에는 concat을 주로 사용했는데 스프레드 연산자를 이용해도 좋을 듯.

const veggie = ["tomato", "cucumber", "beans"];
const newVeggie = veggie.concat();
newVeggie.push("new-value");
console.log(veggie);
console.log(newVeggie);

함수와 스프레드 연산자

인수들을 원소로 가지는 배열에 스프레드 연산자를 사용하면 함수를 쉽게 호출할 수 있다.

function doStuff(x, y, z) {
  console.log(x, y, z);
}

let args = [0, 1, 2];
doStuff.apply(null, args);

// 스프레드 적용
doStuff(...args);
console.log(args);

객체 리터럴과 스프레드(ES2018)

객체에 대해서도 스프레드 연산자를 이용할 수 있다.

let person = {
  name: "Alberto",
  surname: "Montalesi",
  age: 25
};

let clone = { ...person };
console.log(clone);

레스트 매개변수

레스트문법은 점 3개로 이루어졌다는 점은 스프레드와 동일하지만 기능적으로는 반대.
여러 원소를 하나로 '압축'

const runners = ["Tom", "Paul", "Mark", "Luke"];
const [first, second, ...losers] = runners;
console.log(...losers);

객체 리터럴의 업그레이드

변수를 키와 값으로 하는 객체 만들기

아래와 같은 코드가 있다고 하자.

const name = "Alerto";
const surname = "Montalesi";
const age = 25;
const nationality = "Italian";

위 코드를 일반적인 객체리터럴 적용한다면 다음과 같을 것이다.

const person = {
  name: name,
  sname: sname,
  age: age,
  nationality: nationality
};

ES6에서는 다음과 같이 표현할 수 있다.

//변수들의 이름이 코드 내의 속성과 동일하기 때문에 굳이 키를 표기안해도 된다.
const person = {
  name,
  sname,
  age,
  nationality
};

객체에 함수 추가하기

//변수들의 이름이 코드 내의 속성과 동일하기 때문에 굳이 키를 표기안해도 된다.
const person = {
  name: "chaospace",
  greet: function () {
    console.log(this.name);
  }
};
person.greet();

ES6에서는 함수선언시 function키워드를 생략가능

const person = {
  name: "chaospace",
  greet() {
    console.log(this.name);
  }
};
person.greet();

물론 화살표함수를 이용해도 된다.( this에 주의 )

const person = {
  name: "chaospace",
  greet: () => {
    console.log("Hello");
  }
};
person.greet();

객체에 속성 동적정의

변수에 할당된 값을 이용해 객체에 동적인 속성을 추가할 수 있고 접근도 가능
상수를 이용한다면 나름 유용할 듯 싶다.

const name = "myname";
const person = {
  [name]: "chaospace",
  greet: () => {
    console.log("Hello");
  }
};
console.log(person[name]); // chaospace
profile
front-develop

0개의 댓글