Web/JavaScript

JavaScript - Class

ES6 이전

  • ES6 이전에는 Class가 존재하지 않아서 함수가 대신 역할을 했음
// 생성자
function Person({name, age}) {
  this.name = name;
  this.age = age;
}

Person.prototype.getName = function() {
  return this.name;
};

const person = new Person({name: 'kim', age: 24});
console.log(person.getName());  // 출력 값: kim

ES6

  • Class는 ES6에 도입되었음
  • 생성자 선언 시 constructor를 이용함
  • 메소드 선언 시 객체 리터럴에서 사용하던 문법과 유사한 문법을 사용
  • 대괄호를 사용해 변수를 메소드명으로 지정할 수 있음
const methodName = 'getAge';

// 클래스
class Person {
  // 생성자
  constructor({name, age}) {
    this.name = name;
    this.age = age;
  }
  // 메소드가 자동으로 'Person.prototype'에 저장됨
  getName() {
    return this.name;
  }
  // 임의의 표현식
  [methodName]() {
    return this.age;
  }
}

const person = new Person({name: 'kim', age: 24});
console.log(person.getName()); // 출력 값: kim
console.log(person.getAge()); // 출력 값: 24

 

  • Getter, Setter를 정의하고 싶을 때 메소드 앞에 get 또는 set을 붙여주면 됨
// 클래스
class Person {
  // 생성자
  construcor() {
    this.name = 'kim';
    this.age = 24;
  }
  // Getter
  get myName() {
    return this.name;
  }
  // Setter
  set myName(new_name) {
    this.name = new_name;
  }
}

const person = new Person();
person.myName = 'lee';
console.log(person.myName);  // 출력 값: lee

 

  • 클래스 필드
class Counter {
  // class field
  count = 10; 
  
  inc() {
    return this.count++;
  }
}

const counter = new Counter();
console.log(counter.inc()); // 출력 값: 11

 

  • 정적 필드, 정적 메소드
class Counter {
  // static field
  static count = 10; 
  
  // static method
  static inc() {
    return this.count;
  }
}

console.log(Counter.inc());  // 출력 값: 10;

 

  • 클래스 상속
// 부모 클래스
class Parent {
  // ...
}

// 자식 클래스
class Child extends Parent {
  // ...
}

 

  • super
class Melon {
  getColor() {
    return '제 색깔은 초록색입니다.';
  }
}

class WaterMelon extends Melon {
  getColor() {
    return super.getColor() + ' 하지만 속은 빨강색입니다.';
  }
}

const waterMelon = new WaterMelon();
waterMelon.getColor(); // 제 색깔은 초록색입니다. 하지만 속은 빨강색입니다.

 

참고 링크 1: https://helloworldjavascript.net/pages/270-class.html

 

'Web > JavaScript' 카테고리의 다른 글

JavaScript - Prototype  (0) 2021.09.13
JavaScript - JSON String ↔ JSON Object  (0) 2021.09.11
JavaScript - Object 타입  (0) 2021.09.08
JavaScript - DOM 요소 선택자 (요소 접근)  (0) 2021.09.08
JavaScript - 조건문, 반복문  (0) 2021.09.08