클래스는 class 키워드를 사용하여 정의한다
const Person = class {}; // 익명 클래스 표현식 const Person = class MyClass{}; // 가명 클래스 표현식
클래스를 표현식으로 정의할 수 있다는 것은 클래스가 값으로 사용할 수 있는 일급 객체라는 것을 의미하고, 다음과 같은 특징을 갖는다
const Person = ''; { // 호이스팅이 발생하지 않는다면 ''이 출력되어야 한다. console.log(Person); // ReferenceError: Cannot access 'Person' before initialization // 클래스 선언문 class Person {}; }
class Person {} // 인스턴스 생성 const me = new Person(); console.log(me); // Person {} class Person {} // 클래스를 new 연산자 없이 호출하면 타입 에러가 발생한다 const me = Person(); // TypeError: Class constructor Foo cannot be invoked without 'new'
constructor는 인스턴스를 생성하고 초기화하기 위한 특수한 메서드이며, 이름을 변경할 수 없다class Person { // 생성자 constructor(name) { // 인스턴스 생성 및 초기화 this.name = name; } }
prototype 프로퍼티가 가리키는 프로토타입 객체의 constructor 프로퍼티는 클래스 자신을 가리키고 있다constructor 내부에서 this에 추가한 프로퍼티가 인스턴스의 프로퍼티로 추가된 것을 확인할 수 있다constructor 내부의 this는 생성자 함수와 마찬가지로 클래스가 생성한 인스턴스를 가리킨다constructor 메서드를 확인할 수 없다constructor가 단순한 메서드가 아니라는 것을 의마한다constructor는 메서드로 해석되는 것이 아니라 클래스가 평가되어 생성한 함수 객체코드의 일부가 된다constructor의 기술된 동작을 하는 함수 객체가 된다constructor는 클래스 내에 최대 한 개만 존재할 수 있다.constructor는 생략할 수 있다. 생략하면 빈 constructor가 암묵적으로 정의된다.constructor를 생략해서는 안된다.constructor는 별도의 반환문을 갖지 않아야 한다. 암묵적으로 this, 즉 인스턴스를 반환하기 때문이다.class Person { constructor(name) { this.name = name; } sayHi() { console.log(`Hi, ${this.name}`) } } const me = new Person("Lee"); me.sayHi(); // Hi, Lee
static 키워드를 붙이면 적적 메서드(클래스 메서드)가 된다class Person { constructor(name) { this.name = name; } static sayHi() { console.log("Hi") } } Person.sayHi(); // Hi
function 키워드를 생략한 메서드 축약 표현을 사용한다strict mode로 실행된다for...in 문이나 Object.keys 메서드 등으로 열거할 수 없다. 즉, 프로퍼티의 열거 기능 여부를 나타내며, 불리언 값을 갖는 프로퍼티 어트리뷰트 [[Ebumerable]]의 값이 false다[[Construct]]를 갖지 않는 non-constructor다. 따라서 new 연산자와 함께 호출할 수 없다new 연산자와 함께 클래스를 호출하면 생성자 함수와 마찬가지로 클래스의 내부 메서드[[Constructor]]가 호출된다new 연산자와 함께 클래스를 호출하면 constructor 내부 코드가 실행되기에 앞서 암묵저긍로 빈 객체가 생성된다prototype 프로퍼티가 가리키는 객체가 설정된다, 그리고 인스턴스는 this에 바인딩된다constructor의 내부 코드가 실행되어 this에 바인딩되어 있는 인스턴스를 초기화한ㄷconstructor가 인수로 전달받은 초기값으로 인스턴스의 프로퍼티 값을 초기화한다custructor가 생략되었다면 이 과정도 생략된다this가 암묵적으로 반환된다constructor 내부에서 정의해야 한다class Person { constructor(name) { // 인스턴스 프로퍼티 this.name = name; } } const me = new Person("Lee"); console.log(me); // Person {name: "Lee"}
constructor 내부 코드가 실행되기 이전에 이미 this에는 빈 객체(인스턴스)가 바인딩되어 있다constructor 내부에서 this에 인스턴스 프로퍼티를 추가한다getter, setter 함수로 구성되어 있다class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } // fullName은 접근자 함수로 구성된 접근자 프로퍼티다 // getter 함수 get fullName() { return `${this.firstName} ${this.lastName}` } // setter 함수 set fullName(name) { [this.firstName, this.lastName] = name.split(" "); } } const me = new Person("bw", "Lee"); // 데이터 프로퍼티를 통한 프로퍼티 값의 참조 console.log(me.firstName); // 'bw Lee' // 접근자 프로퍼티를 통한 프로퍼티 값의 저장 // fullName에 값을 저장하면 setter 함수가 호출된다. me.fullName = "Heegun Lee"; console.log(me); // {firstName: "Heegun", lastName: "Lee"} // 접근자 프로퍼티를 통한 프로퍼티 값의 참조 // fullName에 접근하면 getter 함수가 호출된다. console.log(me.fullName); // 'Heegun Lee' // fullName은 접근자 프로퍼티다 // 접근자 프로퍼티는 get, set, enumerable, configurable 프로퍼티 어트리뷰트를 갖는다 console.log(Object.getOwnPropertyDescriptor(Person.prototype, 'fullName')); // {get: f, set: f, enumerable: false, configurable: true}
setter는 무엇인가를 프로퍼티에 할당해야 할 때 사용하므로 반드시 매개변수가 있어야한다constructor 내부에서 this에 프로퍼티를 추가해야 한다고 위에서 기술하였다this에 클래스 필드를 바인딩해서는 안된다this는 constructor와 메서드 내에서만 유효하다class Person { name = "Lee"; constructor() { console.log(name); // ReferenceError // 클래스 필드를 참조할 경우 this를 사용해야 한다. } } const me = new Person(); console.log(me); // Person {name: "Lee"}
constructor 밖에서 클래스 필드를 정의할 필요가 없다public이다private 필드를 정의할 수 있는 새로운 표준 사양이 제안되어 있다class Person { #name = ""; constructor(name) { // private 필드 참조 this.#name = name; } } const me = new Person("Lee"); // private 필드 #name은 클래스 외부에서 참조할 수 없다. console.log(me.#name); // SyntaxError
private 필드의 선두에는 # 을 붙여준다, 참조할 때도 마찬가지다private 필드는 클래스 내부에서만 참조할 수 있다extends 키워드를 사용하여 상속받을 클래스를 정의한다extends 키워드는 클래스뿐만 아니라 생성자 함수를 상속받아 클래스를 확장할 수도 있다extends 키워드 앞에는 반드시 클래스가 와야한다// 생성자 함수 function Base(a) { this.a = a; } // 생성자 함수를 상속받는 서브클래스 class Derived extends Base {} const derived = new Drived(1); console.log(derived); // Derived {a: 1}
exnteds 키워드 다음에는 클래스 뿐만이 아니라 [[Construct]] 내부 메서드를 갖는 함수 객체로 평과될 수 있는 모든 표현식을 사용할 수 있다constructor를 생략하면 비어있는 constructor가 암묵적으로 정의된다constructor를 생략하면 다음과 같은 constructor가 암묵적으로 정의된다constructor(...args) { super(...args); }super 키워드는 함수처럼 호출할 수도 있고 식별자처럼 참조할 수 있는 특수한 키워드다super를 호출하면 수퍼클래스의 constructor를 호출한다super를 참조하면 수퍼클래스의 메서드를 호출할 수 있다super 호출super를 호출하면 수퍼클래스의 constructor를 호출한다class Base(a) { constructor(a) { this.a = a; } } class Derived extends Base { // 다음과 같이 암묵적으로 constructor가 정의된다. // constructor(...args) { super(...args); } } const derived = new Drived(1); console.log(derived); // Derived {a: 1}
new 연산자와 함께 Drived 클래스를 호출하면서 전달한 인수1은 Drived 클래스의  Constructor에 전달되고 super 호출을 통해 Base 클래스의 constructor에 전달된다super를 호출할 때 주의할 사항은 다음과 같다constructor를 생략하지 않는 경우 서브클래스의 constructor에서는 반드시 super를 호출해야 한다constructor에서 super를 호출하기 전에는 this를 참조할 수 없다constructor에서만 호출한다. 서브클래스가 아닌 클래스의 constructor나 함수에서 super를 호출하면 에러가 발생한다super 참조super를 참조하면 수퍼클래스의 메서드를 호출할 수 있다class Base { constructor(name) { this.name = name; } sayHi() { return `Hi, ${this.name}` } } // 서브클래스 class Derived extends Base { sayHi() { // super.sayHi는 수퍼클래스의 프로토타입 메서드를 가리킨다 return `${super.sayHi()}. how are you donig?` } } const derived = new Derived("Lee"); console.log(derived.sayHi()); // Hi, Lee. how are you doing?
this는 인스턴스를 가리킨다Base.prototype에 존재하는 sayHi 메서드이기 때문에 this를 사용하면 안된다super 호출base 또는 derived를 값으로 갖는 내부 슬롯 [[ConstructorKind]]를 갖는다constructor에서 반드시 super를 호출해야 하는 이유다constructor 내부에 super 호출이 없으면 에러가 발생한다this 바인딩constructor 내부의 코드가 실행되기 이전에 암묵적으로 빈 객체를 생성한다. 이 빈 객체가 바로 클래스가 생성한 인스턴스다. 그리고 이 인스턴스는 this에 바인딩된다constructor 내부의 this는 인스턴스를 가리킨다constructor가 실행되어 this에 바인딩되어 있는 인스턴스를 초기화한다constructor로의 복기와 this 바인딩constructor로 돌아온다. 이때 super가 반환한 인스턴스가 this에 바인딩된다.super가 반환한 인스턴스를 this에 바인딩하여 그대로 사용한다.super가 호출되지 않으면 서브클래스 constructor에서 this가 생성되지 않는다.super 호춣 이후, 서브클래스의 constructor에 기술되어 있는 인스턴스 초기화가 실행된다this에 바인딩되어 있는 인스턴스에 프로퍼티를 추가한다this가 반환된다extends 키워드 다음에는 [[Construct]] 내부 메서드를 갖는 함수 객체로 평가될 수 있는 모든 표현식을 사용할 수 있다