ES6 class 본문

2021 프론트 엔드 로드맵 따라가기/JS

ES6 class

알 수 없는 사용자 2021. 6. 5. 18:10

앞서 공부했던 OOP의 개념을 ES6에서는 class를 이용해 문법적 이득(syntatic sugar)을 취하며 구현할 수 있다.

물론 prototype 기반으로 작동하며 원리 또한 거의 비슷하다.

 

class Person {
  constructor(firstName, lastName, dob) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthday = new Date(dob);
  }

  greeting() {
    return `Hello there ${this.firstName} ${this.lastName}`;
  }

  calculateAge() {
    const diff = Date.now() - this.birthday.getTime();
    const ageDate = new Date(diff);

    return ageDate.getUTCFullYear() - 1970;
  }

  getMarried(newLastName) {
    this.lastName = newLastName;
  }
}

const jian = new Person("jian", "dev", "11-23-1993");

console.log(jian);

console.log(jian.greeting());

console.log(jian.calculateAge());

jian.getMarried("John");

console.log(jian);

 

Static method

인스턴스화를 하지 않고도 사용할 수 있는 메서드를 뜻한다. ex) Math.random() ..

아래와 같이 메서드 앞에 static 키워드를 이용해 구현 가능하다.

인스턴스로 호출하면 에러가 발생하고, 인스턴스를 선택하는 this 키워드를 사용할 수 없음에 주의하자

 

class Person {
  constructor(firstName, lastName, dob) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthday = new Date(dob);
  }

  greeting() {
    return `Hello there ${this.firstName} ${this.lastName}`;
  }

  calculateAge() {
    const diff = Date.now() - this.birthday.getTime();
    const ageDate = new Date(diff);

    return ageDate.getUTCFullYear() - 1970;
  }

  getMarried(newLastName) {
    this.lastName = newLastName;
  }

  static addNumbers(x, y) {
    return x + y;
  }
}

const jian = new Person("jian", "dev", "11-23-1993");

console.log(jian.addNumbers(1, 2)); // error

console.log(Person.addNumbers(1, 2)); // 3

'2021 프론트 엔드 로드맵 따라가기 > JS' 카테고리의 다른 글

ES5에서 static 메서드를 선언하기  (0) 2021.06.06
ES6 class Inheritance  (0) 2021.06.05
[중요] Prototypal inheritance  (0) 2021.06.05
Prototype  (0) 2021.06.05
Built in Constructor  (0) 2021.06.05
Comments