
자바스크립트는
프로토타입 기반 객체지향 언어다.
프로토타입 기반 객체지향 언어는 클래스가 필요없는 객체지향 프로그래밍 언어다.
ES6에서 도입된 클래스는 기존 프로토타입 기반의 패턴을 클래스 기반 객체지향 프로그래밍에 익숙해지기 쉽도록 새로운 객체 생성 메커니즘을 제시한다.
기존 프로토타입 기반 객체지향 모델을 폐지하고 새롭게 클래스 기반 객체지향 모델을 제공하는 것은 아니다. 클래스는 생성자 함수와 매우 유사하게 동작하지만 다음 몇 가지 차이가 있다.
new 연산자 없이 호출하면 에러가 발생한다. 하지만 생성자 함수를 new 연산자 없이 호출하면 일반 함수로서 호출된다.extends와 super 키워드를 제공한다. 하지만 생성자 함수는 extends와 super 키워드를 지원하지 않는다.strict mode가 지정되어 실행되며 strict mode를 해제할 수 없다. 하지만 생성자 함수는 암묵적으로 strict mode가 지정되지 않는다.constructor, 프로토타입 메서드, 정적 메서드는 모두 프로퍼티 어트리뷰트 [[Enumerable]]의 값이 false다. 다시 말해, 열거되지 않는다.➔ 따라서 클래스를 프로토타입 기반 객체 생성 패턴의 단순한 문법적 설탕이라고 보기보다는, 새로운 객체 생성 메커니즘으로 보는 것이 좀 더 합당하다.
클래스는 class 키워드를 사용해 정의하며 클래스 이름은 생성자 함수와 마찬가지로 파스칼 케이스를 사용하는 것이 일반적이다.
// 클래스 선언문
class Person {}
클래스는 일급 객체로서 다음과 같은 특징을 갖는다.

클래스는 함수로 평가된다
const Person = '';
{
// 호이스팅이 발생하지 않는다면 ''이 출력되어야 한다.
console.log(Person);
// ReferenceError: Cannot access 'Person' before initialization
// 클래스 선언문
class Person {}
}
클래스 선언문으로 정의한 클래스는
constructor다.클래스 선언문도
let, const 키워드로 선언한 변수처럼 호이스팅 되어 선언과 초기화가 분리되어 진행되기 때문에 클래스는 생성자 함수이며 new 연산자와 함께 호출되어 인스턴스를 생성한다.
함수는
new 연산자의 사용 여부에 따라 일반 함수로 호출되거나 클래스는
new 연산자와 함께 호출해야 한다.class Person {}
// 인스턴스 생성
const me = new Person();
console.log(me); // Person {}
// 클래스를 new 연산자 없이 호출하면 타입 에러가 발생한다.
const you = Person();
// TypeError: Class constructor Foo cannot be invoked without 'new'
클래스 몸체에는 0개 이상의 메서드만 선언할 수 있다.
클래스 몸체에서 정의할 수 있는 메서드는 세 가지가 있다.
constructor(생성자)constructorconstructor는
class Person {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
}
클래스는 평가되어 함수 객체가 되어
모든 함수 객체가 가지고 있는 prototype 프로퍼티가 가리키는 프로토타입 객체의 constructor 프로퍼티는 클래스 자신을 가리킨다
new 연산자와 함께 클래스를 호출하면 클래스는 인스턴스를 생성한다.constructor는 메서드로 해석되는 것이 아니라 클래스가 평가되어 생성한 함수 객체 코드의 일부가 된다. constructor는 생성자 함수와 유사하지만 몇가지 차이가 있는데,
constructor는 클래스 내에 최대 한 개만 존재할 수 있다.
constructor를 생략하면 빈 객체를 생성한다.
constructor 내부에서 this에 인스턴스 프로퍼티를 추가한다.constructor를 생략해서는 안된다.constructor는 별도의 반환문을 갖지 않아야 한다.
new 연산자와 함께 클래스가 호출되면 생성자 함수와 동일하게 암묵적으로 this, 즉 인스턴스를 반환하기 때문this가 아닌 다른 객체를 명시적으로 반환하면 인스턴스(this)가 반환되지 못하로 return 문에 명시한 객체가 반환된다.constructor 내부에서 명시적으로 this가 아닌 다른 값을 반환하는 것은 클래스의 기본 동작을 훼손하므로 constructor 내부에서 return 문은 반드시 생략해야 한다생성자 함수를 사용하여 인스턴스를 생성하는 경우
prototype 프로퍼티에 메서드를 추가하지 않아도 기본적으로 프로토타입 메서드가 된다.class Person {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
// 프로토타입 메서드
sayHi() {
console.log(`Hi! My name is ${this.name}`);
}
}
const me = new Person('Lee');
me.sayHi(); // Hi! My name is Lee
// me 객체의 프로토타입은 Person.prototype이다.
Object.getPrototypeOf(me) === Person.prototype; // -> true
me instanceof Person; // -> true
// Person.prototype의 프로토타입은 Object.prototype이다.
Object.getPrototypeOf(Person.prototype) === Object.prototype; // -> true
me instanceof Object; // -> true
// me 객체의 constructor는 Person 클래스다.
me.constructor === Person; // -> true
클래스가 생성한 인스턴스는
결국 클래스는 생성자 함수와 같이 인스턴스를 생성하는 생성자 함수라고 볼 수 있다.
다시 말해, 클래스는 생성자 함수와 마찬가지로 프로토타입 기반의 객체 생성 메커니즘이다.
static) 메서드정적 메서드는 인스턴스를 생성하지 않아도 호출할 수 있는 메서드를 말한다
static 키워드를 붙이면 정적 메서드가 된다.class Person {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
// 정적 메서드
static sayHi() {
console.log('Hi!');
}
}
// 정적 메서드는 클래스로 호출한다.
// 정적 메서드는 인스턴스 없이도 호출할 수 있다.
Person.sayHi(); // Hi!
// 인스턴스 생성
const me = new Person('April');
me.sayHi(); // TypeError: me.sayHi is not a function
정적 메서드는
class Square {
// 정적 메서드
static area(width, height) {
return width * height;
}
}
console.log(Square.area(10, 10)) // 100
class Square {
constructor(width, height) {
this.width = width;
this.height = height;
}
// 프로토타입 메서드
area() {
return this.width * this.height;
}
}
const square = new Square(10, 10)
console.log(square.area()) // 100
프로토타입 메서드와 정적 메서드는 내부의 this 바인딩이 다르다
this를 사용해야 하며, this를 사용하지 않게된다this를 사용하지 않더라도 프로토타입 메서드로 정의할 수 있지만this를 사용하지 않는 메서드는 정적 메서드로 정의하는 것이 좋다💡 표준 빌트인 객체인
Math,Number,JSON,Object,Reflect등은 다양한 정적 메서드를 가지고 있어
애플리케이션 전역에서 사용할 유틸리티 함수다
function 키워드를 생략한 메서드 축약 표현을 사용한다.strict mode로 실행된다.for ... in 문이나 Object.keys 메서드 등으로 열거할 수 없다. 즉, 프로퍼티의 열거 가능 여부를 나타내며, 불리언 값을 갖는 프로퍼티 어트리뷰트 [[Enumerable]]의 값이 false다.[[Construct]]를 갖지 않는 non-constructor다. 따라서 new 연산자와 함께 호출할 수 없다.new 연산자와 함께 클래스를 호출하면 생성자 함수와 마찬가지로 클래스의 내부 메서드 [[Construct]]가 호출된다.
이때 아래의 과정을 거쳐 인스턴스가 생성된다
this 바인딩new 연산자와 함께 클래스를 호출하면 constructor 내부 코드가 실행되기에 앞서 암묵적으로 빈 객체가 생성prototype 프로퍼티가 가리키는 객체가 설정this에 바인딩된다this에 바인딩되어 있는 인스턴스에 프로퍼티를 추가하고constructor가 인수로 전달받은 초기값으로 인스턴스의 프로퍼티 값을 초기화한다this가 암묵적으로 반환된다.인스턴스 프로퍼티는 constructor 내부에서 정의해야 한다
constructor 내부에서 this에 추가한 프로퍼티는 언제나 클래스가 생성한 인스턴스의 프로퍼티가 된다.
class Person {
constructor(name) {
// 인스턴스 프로퍼티
this.name = name;
}
}
const me = new Person('April');
console.log(me); // Person {name: "April"}
class Person {
constructor(name) {
// 인스턴스 프로퍼티
this.name = name; // name 프로퍼티는 public하다.
}
}
const me = new Person('April');
// name은 public하다.
console.log(me.name); // April
접근자 프로퍼티는
[[Value]]을 갖지 않고 getter 함수와 setter 함수로 구성되어 있다.getter 는 인스턴스 프로퍼티에 접근할 때setter 는 인스턴스 프로퍼티에 값을 할당할 때getter는 이름 그대로 무언가를 취득할 때 사용하므로 반드시 무언가를 반환해야 하고 setter는 무언가를 프로퍼티에 할당 해야할 때 사용하므로 반드시 매개변수가 있어야 한다. setter는 단 하나의 값만 할당받기 때문에 단 하나의 매개변수만 선언할 수 있다.클래스 필드(필드 또는 멤버)란
constuctor에서 인스턴스 프로퍼티를 정의하는 기존방식을 사용하고, constructor에서 인스턴스 프로퍼티를 정의하는 방식과 private 필드 정의 제안자바스크립트는 캡슐화를 완전하게 지원하지 않는다
private, public, protected 키워드와 같은 접근 제한자를 지원하지 않는다. 언제나 public 이다
하지만 자바스크립트에서도 private 필드를 정의할 수 있는 새로운 표준 사양이 제안되어 있다. (아직 표준 사양은 아님.. 그러나 최신 브라우저와 최신 Node.js에서는 이미 구현되어 있음)
private 필드의 선두에는 #을 붙여준다. private 필드를 참조할 때도 #을 붙여주어야 한다. private 필드는 클래스 내부에서만 참조할 수 있다. 또한, private 필드는 반드시 클래스 몸체에 정의해야 한다.| 접근 가능성 | public | private |
|---|---|---|
| 클래스 내부 | O | O |
| 자식 클래스 내부 | O | X |
| 클래스 인스턴스를 통한 접근 | O | X |
class Person {
// private 필드 정의
#name = '';
constructor(name) {
// private 필드 참조
this.#name = name;
}
}
const me = new Person('Lee');
// private 필드 #name은 클래스 외부에서 참조할 수 없다.
console.log(me.#name);
// SyntaxError: Private field '#name' must be declared in an enclosing class
static 필드 정의 제안static public필드, static private 필드, static private 메서드를 정의할 수 있는 새로운 표준 사양인 Static class features가 제안되어 있다.
** **
class MyMath {
// static public 필드 정의
static PI = 22 / 7;
// static private 필드 정의
static #num = 10;
// static 메서드
static increment() {
return ++MyMath.#num;
}
}
console.log(MyMath.PI); // 3.142857142857143
console.log(MyMath.increment()); // 11
상속에 의한 클래스 확장은
extends)하여 정의하는 것
클래스와 생성자 함수는 인스턴스를 생성할 수 있는 함수라는 점에서 매유 유사하지만,
extends 키워드가 기본적으로 제공된다.extends 키워드상속을 통해 클래스를 확장하려면 extends 키워드를 사용하여 상속받을 클래스를 정의한다.
// 수퍼(베이스/부모)클래스
class Base {}
// 서브(파생/자식)클래스
class Derived extends Base {}
extends 키워드의 역할은
extends 키워드는
extends 키워드 앞에는 반드시 클래스가 와야 한다// 생성자 함수
function Base (a) {
this.a = a;
}
// 생성자 함수를 상속받는 서브클래스
class Derived extends Base {}
const derived = new Derived(1);
console.log(derived); // Derived {a: 1}
extends 키워드 다음에는
[[Construct]] 내부 메서드를 갖는 함수 객체로 평가될 수 있는 모든 표현식을 사용할 수 있다. function Base1() {}
class Base2 {}
let condition = true;
// 조건에 따라 동적으로 상속 대상을 결정하는 서브클래스
class Derived extends (condition ? Base1 : Base2) {}
const derived = new Derived();
console.log(derived); // Derived {}
console.log(derived instanceof Base1); // true
console.log(derived instanceof Base2); // false
constructorconstructor를 생략하면 암묵적으로 빈 객체가 정의되는데constructor를 생략하면 클래스에 다음과 같은 constructor가 암묵적으로 정의된다.args는 new 연산자와 함께 클래스를 호출할 때 전달한 인수의 리스트다consturctor를 생략하면 빈 객체가 생성된다. constructor를 생략하면 클래스에 다음과 같은 constructor가 암묵적으로 정의된다.constructor(...args) { super(...args); }
super 키워드super 키워드는
this와 같이 식별자처럼 참조할 수 있는super 키워드는 이렇게 동작한다.
super를 호출하면 수퍼클래스의 constructor(super-constructor)를 호출super를 참조하면 수퍼클래스의 메서드를 호출할 수 있다super 호출super를 호출하면 수퍼클래스의 constructor(super-constructor)를 호출한다
super 호출할 때 주의할 점은,
constructor을 생략하지 않는 경우 서브클래스의 constructor에서는 반드시 super를 호출해야 한다.class Base {}
class Derived extends Base {
constructor() {
// ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
console.log('constructor call');
}
}
const derived = new Derived();
constructor에서 super를 호출하기 전에는 this를 참조할 수 없다.class Base {}
class Derived extends Base {
constructor() {
// ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
this.a = 1;
super();
}
}
const derived = new Derived(1);
super는 반드시 서브클래스의 constructor에서만 호출한다. 서브클래스가 아닌 클래스의 constructor나 함수에서 super를 호출하면 에러가 발생한다.class Base {
constructor() {
super(); // SyntaxError: 'super' keyword unexpected here
}
}
function Foo() {
super(); // SyntaxError: 'super' keyword unexpected here
}
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 doing?`;
}
}
const derived = new Derived('April');
console.log(derived.sayHi()); // Hi! April. how are you doing?
// 수퍼클래스
class Base {
static sayHi() {
return 'Hi!';
}
}
// 서브클래스
class Derived extends Base {
static sayHi() {
// super.sayHi는 수퍼클래스의 정적 메서드를 가리킨다.
return `${super.sayHi()} how are you doing?`;
}
}
console.log(Derived.sayHi()); // Hi! how are you doing?
상속 관계에 있는 두 클래스가 어떻게 협업하며 인스턴스를 생성하는지 이해하면 super를 더욱 명확하게 이해할 수 있다
직사각형을 추상화한 Rectangle 클래스와 상속을 통해 Rectangle 클래스를 확장한 ColorRectangle 클래스다
// 수퍼클래스
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
toString() {
return `width = ${this.width}, height = ${this.height}`;
}
}
// 서브클래스
class ColorRectangle extends Rectangle {
constructor(width, height, color) {
super(width, height);
this.color = color;
}
// 메서드 오버라이딩
toString() {
return super.toString() + `, color = ${this.color}`;
}
}
const colorRectangle = new ColorRectangle(2, 4, 'red');
console.log(colorRectangle); // ColorRectangle {width: 2, height: 4, color: "red"}
// 상속을 통해 getArea 메서드를 호출
console.log(colorRectangle.getArea()); // 8
// 오버라이딩된 toString 메서드를 호출
console.log(colorRectangle.toString()); // width = 2, height = 4, color = red
서브클래스 colorRectangle이 new 연산자와 함께 호출되면 다음 과정을 통해 인스턴스를 생성한다.
super 호출자바스크립트 엔진은 클래스를 평가할 때 수퍼클래스와 서브클래스를 구분하기 위해 base 또는 derived를 값으로 갖는 내부 슬롯 [[ConstructorKind]]를 갖는다
base: 다른 클래스를 상속받지 않는 클래스, 그리고 생성자 함수derived: 다른 클래스를 상속받는 서브 클래스이를 통해 new 연산자와 함께 호출되었을 때의 동작이 구분된다.
new 연산자가 함께 호출되었을 때 암묵적으로 빈 객체, 즉 인스턴스를 생성하고 this에 바인딩한다. constructor에서 반드시 super를 호출해야 하는 이유다.this 바인딩수퍼클래스 constructor의 내부의 코드가 실행되기 이전에 암묵적으로 빈 객체를 생성하고
this에 바인딩된다.constructor의 내부의 this는 생성된 인스턴스(빈 객체)를 가리킨다. new와 함께 호출된 함수를 가리키는 new.target은 서브클래스를 가리킨다.new.target이 가리키는 서브클래스가 생성한 것으로 처리된다.prototype 프로퍼티가 가리키는 객체(Rectangle.prototype)가 아니라new.target, 즉 서브클래스의 prototype 프로퍼티가 가리키는 객체(ColorRectangle.prototype)이다.수퍼클래스의 constructor가 실행되어 this에 바인딩되어 있는 인스턴스를 초기화한다.
this에 바인딩 되어 있는 인스턴스에 프로퍼티를 추가하고 constructor가 인수로 전달받은 초기값으로 인스턴스의 프로퍼티를 초기화한다.super의 호출의 종료되고 제어 프름이 서브클래스 constructor로 돌아온다.
super가 반환한 인스턴스가 this에 바인딩된다. super가 반환한 인스턴스를 this에 바인딩하여 그대로 사용한다. super가 호출되지 않으면 인스턴스가 생성되지 않으며,this 바인딩도 할 수 없다.constructor에서 super를 호출하기 전에는 this를 참조할 수 없는 이유가 바로 이 때문이다.super 호출 이후,
consstructor에 기술되어 있는 인스턴스 초기화가 실행된다. this에 바인딩되어 있는 인스턴스에 프로퍼티를 추가하고 constructor가 인수로 전달받은 초기값으로 인스턴스의 프로퍼티를 초기화한다.클래스의 모든 처리가 끝나면 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
표준 빌트인 객체 또한 [[Construct]] 내부 메서드를 갖는 생성자 함수이므로 extends 키워드를 사용하여 확장할 수 있다.