우와한 개발자

[JavaScript] ES6 문법 - 클래스, 화살표함수, 구조분해할당, 스프레드

by 우와한개발자

1. ECMAScript란?

  • JavaScript의 표준 명세
버전 주요 버전
ES5 (2009) strict mode, JSON
ES6 (2015) class, arrow function, let/const, 구조분해, 모듈, Promise
ES8 (2017) async/await
ES2023 toSorted, toReversed, findLast 등

 

2. 클래스 Class

  • 함수의 한 종류이지만 function 키워드 대신 class 키워드 사용
  • 생성자 : constructor() → 객체 생성 시 자동 호출
  • 변수를 따로 선언하지 않고 this.변수명 으로 바로 사용
  • extends를 쓴 자식 클래스는 반드시 super()를 먼저 호출해야 this를 사용 가능
class Car {
  constructor(name) {
    this.brand = name;
  }
  present() {
    return `I have a ${this.brand}`;
  }
}

class Model extends Car {
  constructor(name, mod) {
    super(name); // 부모 생성자 먼저 호출 필수
    this.model = mod;
  }
  present() {
    return super.present() + `, it is a ${this.model}`;
  }
}

const mycar = new Model("Ford", "Mustang");
mycar.present(); // "I have a Ford, it is a Mustang"

 

3. 화살표 함수 Arrow Function

  • 함수를 더 짧고 간결하게 작성하는 방법
  • function 키워드 대신 => 사용
  • 본문이 한 줄이면 return 생략 가능
// 기존 함수
function add(a, b) {
    return a + b;
}

// 화살표 함수
const add = (a, b) => a + b;        // return 생략
const double = x => x * 2;          // 매개변수 1개면 괄호 생략
const greet = () => console.log("안녕"); // 매개변수 없으면 () 필요

 

4. 구조분해 할당 (Destructuring)

  • 배열이나 객체의 값을 변수로 쉽게 꺼내는 문법
// 배열 구조분해
const [a, b, c] = [1, 2, 3];
console.log(a); // 1

// 객체 구조분해
const { name, age } = { name: "철수", age: 20 };
console.log(name); // 철수

 

5. 스프레드 연산자 (...)

  • 배열/객체를 펼쳐서 복사하거나 합치는 문법
// 배열 합치기
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1,2,3,4,5]

// 객체 합치기
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a:1, b:2 }

// 함수 인자로 펼치기
const nums = [1, 2, 3];
console.log(Math.max(...nums)); // 3

블로그의 정보

우와한개발자 님의 블로그

우와한개발자

활동하기