자바스크립트 클래스

이희제·2024년 5월 16일
post-thumbnail

ES6부터 클래스 문법이 추가되어 클래스에 대해 살펴보자.

1. 클래스와 인스턴스의 개념 이해

클래스는 하위로 갈수록 상위 클래스의 속성을 상속하면서 더 구체적인 요건이 추가, 변경된다.

클래스의 속성을 지니는 실존하는 개체를 인스턴스라고 한다. 한 인스턴스는 하나의 클래스만을 바탕으로 만들어진다.


2. 자바스크립트의 클래스(ES6 이전 기준)

인스턴스에 상속되는지 여부에 따라 스태틱 멤버(static member)와 인스턴스 멤버(instance member)로 나뉜다.

자바스크립트에서는 인스턴스에서도 직접 메서드를 정의할 수 있어 프로토타입에 명시되어 있는 메서드는 '프로토타입 메서드'라고 부르는 편이다.

var Rectangle = function(width, height) {
  this.width = width;
  this.height = height;
};
Rectangle.prototype.getArea = function() { // 프로토타입 메서드
  return this.width * this.height;
};
Rectangle.isRectangle = function(instance) { //스태틱 메서드
  return (
    instance instanceof Rectangle && instance.width > 0 && instance.height > 0
  );
};

var rect1 = new Rectangle(3, 4);
console.log(rect1.getArea()); // 12 (O)
console.log(rect1.isRectangle(rect1)); // Error (X)
console.log(Rectangle.isRectangle(rect1)); // true

인스턴스에서 직접 호출할 수 있는 메서드가 바로 프로토타입 메서드이다.

스태틱 메서드는 클래스 자체를 this로 해서 직접 접근해야만 호출할 수 있다.


3. ES6의 클래스 및 클래스 상속

ES6에 추가된 class를 활용해서 다음과 같은 기본 문법을 통해 만들 수 있다.

class MyClass {
  // 여러 메서드를 정의할 수 있음
  constructor() { ... } // 생성자
  method1() { ... }
  method2() { ... }
  method3() { ... }
  ...
}
  • constructor()sms new에 의해 자동으로 호출되어, 객체를 초기화할 수 있다.

클래스는 함수의 한 종류이다.

class User {
  constructor(name) { this.name = name; }
  sayHi() { alert(this.name); } // User.prototype에 저장
}

// User가 함수라는 증거
alert(typeof User); // function

class User {...}를 선언하면 다음과 같이 동작한다.

  1. User라는 이름을 가진 함수를 만든다. 함수 본문은 생성자 메서드 constructor에서 가져오고 생성자 메서드가 없으면 본문이 비워진 채로 함수가 만들어진다.

  2. sayHi같은 클래스 내에서 정의한 메서드를 User.prototype에 저장한다. (프로토타입 메서드)

ES5와 ES6의 클래스 문법을 비교해보자.

var ES5 = function(name) {
  this.name = name;
};
ES5.staticMethod = function() {
  return this.name + ' staticMethod';
};
ES5.prototype.method = function() {
  return this.name + ' method';
};
var es5Instance = new ES5('es5');
console.log(ES5.staticMethod()); // es5 staticMethod
console.log(es5Instance.method()); // es5 method

var ES6 = class {
  constructor(name) {
    this.name = name;
  }
  static staticMethod() { // 생성자 함수(클래스) 자신만이 호출할 수 있다.
    return this.name + ' staticMethod';
  }
  method() { // 자동으로 prototye 객체 내부에 할당되는 메서드이다.
    return this.name + ' method';
  }
};
var es6Instance = new ES6('es6');
console.log(ES6.staticMethod()); // es6 staticMethod
console.log(es6Instance.method()); // es6 method

클래스의 상속 예시를 살펴보자.

var Rectangle = class {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  getArea() {
    return this.width * this.height;
  }
};
var Square = class extends Rectangle {
  constructor(width) {
    super(width, width);
  }
  getArea() {
    console.log('size is :', super.getArea());
  }
};
  • super 키워드를 함수처럼 사용할 수 있는데 이는 상위 클래스의 constructor를 실행한다.
  • super 키워드를 객체처럼 사용하면 해당 객체는 상위 클래스의 prototype을 바라본다.
    • 호출한 메서드의 this는 원래의 this를 그대로 따른다.
profile
그냥 하자

0개의 댓글