The Wayback Machine - https://web.archive.org/web/20160608215255/https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes

Classes

현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

JavaScript class는 ECMAScript 6을 통해 소개되었으며, 기존 prototype 기반의 상속을 보다 명료하게 표현 합니다. Class 문법은 새로운 객체지향 상속 모델을 제공하는 것은 아닙니다. JavaScript class는 객체를 생성하고 상속을 다루는데 있어 훨씬 더 단순하고 명확한 문법을 제공합니다.

Class 정의

Class는 사실 함수이다. 함수를 함수 표현식과 함수 선언으로 정의할 수 있듯이 class 문법도 class 표현식과 class 선언 두가지 방법을 제공한다.

Class 선언

class를 정의하는 한가지 방법은 class 선언이다. class를 선언하기 위해서는 클래스의 이름과 함께 class 키워드를 사용해야 한다.

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

Hoisting

함수 선언 과 클래스 선언의 중요한 차이점은 함수 선언의 경우 호이스팅이 일어나지만 클래스 선언은 그렇지 않다는 것이다. 클래스를 사용하기 위해서는 클래스를 먼저 선언 해야 하며 그렇지 않으면 다음과 같은 코드는 ReferenceError를 던질 것이다:

var p = new Polygon(); // ReferenceError

class Polygon {}

Class 표현식

class 표현식은 class를 정의 하는 또 다른 방법이다 . Class 표현식은 이름을 가질 수도 있고 안가질 수도 있다. 이름을 가진 class 표현식의 클래스 이름은 해당 클래스의 body에 대해 local scope에 한해 유효하다.

// unnamed
var Polygon = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

// named
var Polygon = class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

Class body 와 method 정의

class body는 중괄호 {} 로 묶여 있는 안쪽 부분이다. 이곳은 여러분이 method나 constructor와 같은 class members를 정의할 곳이다.

Strict mode

클래스 선언클래스 표현식의 본문(body)은 strict mode 에서 실행된다.

Constructor

constructor 메소드는 class 로 생성된 객체를 생성하고 초기화하기 위한 특수한 메소드이다.  "constructor" 라는 이름을 가진 특수한 메소드는 클래스 안에 한 개만 존재할 수 있다. 만약 클래스가 한 개를 초과하는 constructor 메소드를 포함하면 SyntaxError 가 발생한다.

constructor 는 부모 클래스의 constructor 를 호출하기 위해 super 키워드를 사용할 수 있다.

Prototype methods

method definitions 참조.

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  
  get area() {
    return this.calcArea()
  }

  calcArea() {
    return this.height * this.width;
  }
}

Static methods

static 키워드는 클래스의 정적(static) 메소드를 정의한다. 정적 메소드는 클래스의 인스턴스화(instantiating) 없이 불리며, 클래스가 인스턴스화 되었다면 부를 수 없다. 정적 메소드는 어플리케이션(application)을 위한 유틸리티(utility) 함수를 생성하는데 주로 사용된다.

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    static distance(a, b) {
        const dx = a.x - b.x;
        const dy = a.y - b.y;

        return Math.sqrt(dx*dx + dy*dy);
    }
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);

console.log(Point.distance(p1, p2));

extends 를 통한 클래스 상속(sub classing)

extends 키워드는 클래스 선언이나 클래스 표현식에서 다른 클래스의 자식 클래스를 생성하기 위해 사용된다.

class Animal { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}

class Dog extends Animal {
  speak() {
    console.log(this.name + ' barks.');
  }
}

Sub classing built-in objects

TBD

super 를 통한 상위 클래스 호출

super 키워드는 객체의 부모가 가지고 있는 함수들을 호출하기 위해 사용된다.

class Cat { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}

class Lion extends Cat {
  speak() {
    super.speak();
    console.log(this.name + ' roars.');
  }
}

ES5 상속 문법과 ES6 클래스 문법의 비교

TBD

예제

TBD

명세서

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Class definitions' in that specification.
Standard Initial definition.
ECMAScript 2016 Draft (7th Edition, ECMA-262)
The definition of 'Class definitions' in that specification.
Draft  

브라우저 호환성

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 42.0 Nightly build ? No support 9.0
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support No support Nightly build ? ? 9 42.0

참조

문서 태그 및 공헌자

 이 페이지의 공헌자: maytree, hwshim
 최종 변경: maytree,
HTTPS · web.archive.org
← Home