티스토리 뷰

ES5 와 ES6 비교

 

ES5 프로토타입

// 생성자
function Cat(name, age) {
    this.name = name;
    this.age = age;
}

Cat.prototype.feeding = function() {
    return `${this.name}가 츄르를 먹습니다.`
}

// 인스턴스 생성
let cat = new Cat('금동이', 9);
console.log(cat.feeding()); // 금동이가 츄르를 먹습니다.

 

ES6 클래스

class Cat {
    //생성자
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    feeding() {
        return `${this.name}가 츄르를 먹습니다.`
    }
}

// 인스턴스 생성
let cat = new Cat('라떼', 1);
console.log(cat.feeding()); // 라떼가 츄르를 먹습니다.
  • 클래스 문법은 자바에서 보던 클래스와 매우 유사하다. 다만 자바는 생성자의 이름을 클래스 이름과 동일하게 하여야 하지만 자바스크립트는 constructor로 고정되어 있고 클래스 안에 한 개만 존재할 수 있다.
  • 생성자 내에서 this는 클래스가 생성할 인스턴스를 가리킨다!

 

클래스 메서드

class Calculator {
    add(x, y) {
        return x + y;
    }
    subtract(x, y) {
        return x - y;
    }
}

let calc = new Calculator();
calc.add(1, 3); // 4
  • 클래스 내에서 메서드를 정의!

 

const method1 = 'divide';

class Calculator {
    add(x, y) {
        return x + y;
    }
    subtract(x, y) {
        return x - y;
    }

    [method1](x, y) {
        return x / y;
    }
}
  • 객체 리터럴 문법과 비슷하게 대괄호 안에 표현식을 넣어서 사용할 수도 있다.

 

Getter / Setter

class Product {
  constructor() {
    this.price = 0;
  }
  get price() {
    return this.price;
  }
  set price(newPirce) {
    this.price = newPrice;
  }
}

let iPad = new Product();
iPad.price = 10000; // set이 없다면 에러
iPad.price; // 10000
  • 메서드 이름 앞에 get, set을 붙여줌으로써 정의할 수 있음
  • Getter는 Product.price()를 사용해서 프로퍼티를 읽으려고 할 때 실행
  • Setter는 Product.price = newPrice; 로 값을 할당할 때 실행
반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함