모던 자바스크립트 Deep Dive : 25장 클래스

EdLee·2022년 11월 13일

javascript

목록 보기
15/37

25장 클래스

1. 클래스는 프로토타입의 문법적 설탕인가?


  • 프로토타입과 생성자 함수로 상속을 구현할 수 있다.
  • 그러면 클래스는 왜 필요한 걸까?
  • 생성자 함수와 클래스는 유사하지만, 다음 차이가 있다.
클래스생성자 함수
new 연산자 없이 호출하면 에러 발생new 연산자 없이 호출하면 일반 함수로서 호출
상속을 지원하는 extends와 super 키워드 제공미제공
호이스팅이 발생하지 않는 것처럼 동작함수 선언문으로 정의된 생성자 함수는 함수 호이스팅,
함수 표현식으로 정의한 생성자 함수는 변수 호이스팅 발생
암묵적으로 strict mode 지정되고 해제 불가능암묵적으로 strict mode 지정되지 않음
constructor, 프로토타입 메서드, 정적 메서드는
프로토타입 어트리뷰트 [[Enumerable]]이 false
=> 열거 불가능
열거 가능

2. 클래스의 정의


// 클래스 선언문
class Person {}

// 익명 클래스 표현식
const Person = class {};

// 기명 클래스 표현식
const Person = class MyClass {};
  • 클래스를 표현식으로 정의할 수 있다? => 일급 객체다
  1. 무명의 리터럴로 생성 가능 => 런타임에 생성 가능
  2. 변수나 자료구조(객체, 배열 등)에 저장 가능
  3. 함수의 매개변수에 전달 가능
  4. 함수의 반환값으로 사용 가능

3. 클래스 호이스팅


  • 클래스는 함수로 평가되지만, 정의 이전에 참조할 수는 없다.(let, const 같다😁)
const Person = '';

{
  console.log(Person); // Cannot access 'Person' before initialization
  class Person { }
}

4. 인스턴스 생성


const Person = class MyClass { };

const me = Person(); // TypeError: Class constructor MyClass cannot be invoked without 'new'

// new를 사용해야 한다
const me = new Person();

// MyClass라는 클래스 이름은 클래스 몸체 내부에서만 유효
console.log(MyClass); // MyClass is not defined

const you = new MyClass(); // MyClass is not defined
  • MyClass 이름은 어차피 외부에서 못쓰고, Person 내부에서만 쓰인다.
  • 차라리 익명 클래스로 쓰는게 나을것 같은데😮

5. 메서드


  • 클래스 몸체에서 정의할 수 있는 메서드
  1. constructor(생성자)
  2. 프로토타입 메서드
  3. 정적 메서드

5.1 constructor

  • 인스턴스를 생성하고 초기화하기 위한 특수한 메서드

클래스의 constructor 메서드와 프로토타입의 constructor 프로퍼티
이름이 같아 혼동하기 쉽지만, 직접적인 관련은 없다. 프로토타입의 constructor프로퍼티는 모든 프로토타입이 가지고 있는 프로퍼티이며, 생성자 함수를 가리킨다.

constructor의 특징

  • constructor라는 이름은 변경 불가능
  • 클래스 내에 한 개만 존재 가능
  • 생략 시, 빈 constructor가 암묵적으로 정의된다
  • 암묵적으로 this를 반환한다 (따라서 return은 생략할 것)
  • 클래스가 평가된 결과에 constructor는 존재하지 않는다. 생성된 함수 객체 자체가 constructor의 결과물이기 때문.
class Person {
  constructor(name,address) {
    // 인수로 인스턴스 초기화
    this.name = name;
    this.address = address;
    // return {}; // 이렇게 객체를 반환하면 constructor의 기본 동작을 훼손하는것. return은 반드시 생략할 것.
  }
}

// 인스턴스 프로퍼티가 추가된다.
const me = new Person('Lee','Seoul');
console.log(me); // Person { name: 'Lee', address:'Seoul' }

5.2 프로토타입 메서드

  • 생성자 함수를 사용하여 인스턴스를 생성하는 경우 프로토타입 메서드를 생성하기 위해서는 명시적으로 프로토타입에 메서드를 추가해야만 한다.
  • 클래스 몸체에서 정의한 메서드는 생성자 함수에 의한 객체 생성방식과 다르게.. 클래스의 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
  • 따라서 sayHi()는 클래스의 프로토타입에 있는 하나를 돌려쓴다.

5.3 정적 메서드

  • 정적 메서드 : 인스턴스를 생성하지 않아도 호출할 수 있는 메서드
  • 클래스에서는 메서드에 static 키워드를 붙이면 정적 메서드가 된다.
class Person {
  // 생성자
  constructor(name) {
    // 인스턴스 생성 및 초기화
    this.name = name;
  }

  // 정적 메서드
  static sayHi() { // static 키워드!
    console.log('Hi!');
  }
}

// 정적 메서드는 클래스로 호출한다.
// 정적 메서드는 인스턴스 없이도 호출할 수 있다.
Person.sayHi(); // Hi!

// 인스턴스 생성
const me = new Person('April');
me.sayHi(); // TypeError: me.sayHi is not a function
  • 정적 메서드는 클래스에 바인딩된 메서드
  • 클래스는 그 자체로 함수 객체이므로, 별도 생성 과정이 필요없다.
  • 따라서 인스턴스 없어도 클래스에서 정적 메서드를 호출 가능.

5.4 정적 메서드와 프로토 타입 메서드의 차이

  1. 정적 메서드와 프로토타입 메서드는 자신이 속해 있는 프로토타입 체인이 다르다.
  2. 정적 메서드는 클래스로 호출하고 프로토타입 메서드는 인스턴스로 호출한다.
  3. 정적 메서드는 인스턴스 프로퍼티를 참조할 수 없지만 프로토타입 메서드는 인스턴스 프로퍼티를 참조할 수 있다.
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를 안쓸거면 정적 메서드로 정의할 것

5.5 클래스에서 정의한 메서드의 특징

  1. function 키워드를 생략한 메서드 축약 표현을 사용한다.
  2. 객체 리터럴과는 다르게 클래스에 메서드를 정의할 때는 콤마가 필요 없다.
  3. 암묵적으로 strict mode로 실행된다.
  4. for ... in 문이나 Object.keys 메서드 등으로 열거할 수 없다. 즉, 프로퍼티의 열거 가능 여부를 나타내며, 불리언 값을 갖는 프로퍼티 어트리뷰트 [[Enumerable]]의 값이 false다.
  5. 내부 메서드 [[Construct]]를 갖지 않는 non-constructor다. 따라서 new 연산자와 함께 호출할 수 없다.

6. 클래스의 인스턴스 생성 과정


  • new 연산자와 함께 클래스를 호출하면 생성자 함수와 마찬가지로 클래스의 내부 메서드 [[Construct]]가 호출된다.

인스턴스 생성과 this 바인딩

  • new 연산자와 함께 클래스를 호출하면 constructor 내부 코드가 실행되기에 앞서 암묵적으로 빈 객체가 생성
  • 이때 클래스가 생성한 인스턴스의 프로토타입으로 클래스의 prototype 프로퍼티가 가리키는 객체가 설정
  • 암묵적으로 생성된 빈 객체, 즉 인스턴스는 this에 바인딩된다

인스턴스 초기화

  • this에 바인딩되어 있는 인스턴스에 프로퍼티를 추가
  • constructor가 인수로 전달받은 초기값으로 인스턴스의 프로퍼티 값을 초기화한다

인스턴스 반환

  • 클래스의 모든 처리가 끝나면 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.

7. 프로퍼티


7.1 인스턴스 프로퍼티

  • constructor가 실행되기 전에 이미 인스턴스는 생성되어 있다.
  • 이 인스턴스의 프로퍼티를 constructor에서 정의한다.
class Person {
  constructor(name) {
    // 인스턴스 프로퍼티
    this.name = name; // name 프로퍼티
  }
}

const me = new Person('Lee');

// public하므로 그냥 불러올 수 있다.
console.log(me.name); // Lee

7.2 접근자 프로퍼티

  • 자체적으로 값([[Value]] 내부 슬롯)을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 사용하는 접근자 함수로 구성된 프로퍼티
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('Ungmo','Lee');

console.log(`${this.firstName} ${this.lastName}`); //Ungmo Lee

me.fullName = 'Heegun Lee';
console.log(me); //{firstName : 'Heegun', lastName : 'Lee'}
console.log(me.fullName); // Heegun Lee

// 어차피 public인데 접근자 프로퍼티가 의미가 있나?
me.firstName = 'Ed'
console.log(me.fullName); // Ed Lee
  • 클래스의 메서드는 기본적으로 프로토타입 메서드이므로, 접근자 프로퍼티 또한 인스턴스 프로퍼티가 아닌 프로토타입의 프로퍼티이다.

7.3 클래스 필드 정의 제안

  • 클래스 필드 : 클래스 기반 객체 지향 언어에서 클래스가 생성할 인스턴스의 프로퍼티
  • 앞서 인스턴스 프로퍼티는 "Constructor"에 정의해야 한다고 했다.
  • 그리고 클래스 필드에는 메서드만 정의 가능하다고...
class Person {
 	name = 'Lee'; 
}

const me = new Person();
console.log(me); // Person {name: "Lee"}
  • 그래놓고 위 코드는 오류가 안난다
  • 클래스 필드는 조만간 ECMAscript 표준이 될 예정이고, 최신 브라우저에서는 이미 선반영되어 있기 때문

특징
1. 클래스 필드를 정의하는 경우 this에 클래스 필드를 바인딩하지 말 것(this는 constructor와 메서드 내에만 유효)
2. 클래스 필드를 참조하는 경우 반드시 this를 사용해야 한다.
3. 클래스 필드에 초기값을 할당하지 않으면 undefined를 갖는다.
4. 함수를 클래스 필드에 할당할 수 있다.(클래스필드를 통해 메서드를 정의할 수 있다.)

//1. this에 클래스 필드를 바인딩해서는 안된다.
class Person {
  this.name = " "; //SyntaxError : Unexpected token '.'
}

// 2. 클래스 필드 참조 시, 반드시 this 사용
class Person {
  name = 'Lee';
  constructor() {
    console.log(name); //ReferenceError : name is not defined
  }
}

// 3. 클래스 필드를 초기화하지 않으면 undefined를 갖는다.
class Person{
  name;
}
const me = new Person();
console.log(me); // Person{name : undefined}

// 4. 함수를 클래스 필드에 할당할 수 있다.
class Person{
  //클래스 필드
  name = 'Lee';

  //클래스 필드에 함수를 할당
  getName = function(){
    return this.name;
  }
  //화살표 함수로 정의할 수도 있다.
  //getName = () => this.name;
}
const me = new Person();
console.log(me); //Person{name : "Lee", getName: f}
console.log(me.getName()); //Lee

7.4 private 필드 정의 제안

  • 앞서 js는 private을 완전히 지원하지 않는다고 했는데..😒
  • private도 표준으로 채택이 될 예정이며, 브라우저에 이미 선반영되어 있다😶
class Person{
  // private 정의
  #name = '';
	
  constructor(name){
	this.#name = name;
  }

  //name접근자 프로퍼티다.
  get name(){
    //private 필드를 참조하여 trim한 다음 반환한다.
    return this.name.trim();
  }
}

const me = new Person('Lee');
console.log(me.name);	//Lee
  • 참조를 할때에도 #을 붙여준다.
  • 외부에서 참조할 수 없다.
  • 접근자 프로퍼티를 통해 간접적으로 접근 할 수 있다.
  • private필드는 반드시 클래스 몸체에 정의해야 하며, constructor에 정의하면 에러가 발생한다.
접근 가능성publicprivate
클래스 내부OO
자식 클래스 내부OX
클래스 인스턴스를 통한 접근OX

7.5 static 필드 정의 제안

  • 마찬가지로 static도 표준 예정
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

8. 상속에 의한 클래스 확장


8.1 클래스 상속과 생성자 함수 상속

  • 프로토타입 기반 상속 : 프로토타입 체인을 통해 다른 객체의 자산을 상속받는 개념
  • 상속에 의한 클래스 확장 : 기존 클래스를 상속받아 새로운 클래스를 확장하여 정의
class Animal{
  constructor(age, weight){
    this.age = age;
    this.weight = weight;
  }
  
  eat() { return 'eat'; }
  
  move() { return 'move'; }
}

//상속을 통해 Animal클래스를 확장한 Bird 클래스
class Bird extends Animal { // extends 키워드 사용
  fly() { return 'fly';}
}

const bird = new Bird(1,5);

console.log(bird); // Bird{age : 1, weight : 5}
console.log(bird instanceof Bird); // true;
console.log(bird instanceof Animal); // true;

console.log(bird.eat()); // eat
console.log(bird.move()); // move
console.log(bird.fly()); // fly
  • 위 상속은 다음과 같은 프로토타입 체인을 갖는다

8.2 extends 키워드

  • extends : 클래스 확장을 위해 상속받을 클래스를 정의
//수퍼(베이스/부모)클래스
class Base{}

//서브(파생/자식)클래스
class Derived extends Base{}

extends의 역할

  • 수퍼클래스와 서브클래스 간의 상속 관계를 정의
  • 클래스 간의 프로토타입 체인 생성(프로토타입 메서드, 정적 메서드 모두 상속 가능)

8.3 동적 상속

  • extends 키워드를 사용해 생성자 함수를 상속받아 클래스를 확장할 수 있다.
  • 단, extends 키워드 에는 반드시 클래스가 와야 한다.
//생성자 함수
function Base(a){
  this.a = a;
}

//생성자 함수를 상속받는 서브 클래스
class Derived extends Base{}

const derived = new Derived(1);
console.log(derived);	//Derived{a:1}
  • 즉, 수퍼 클래스는 클래스, 생성자 함수 등 [[Construct]] 내부 메서드를 갖는 모든 표현식을 사용할 수 있다.
  • 하지만 서브 클래스는 무조건 클래스여야 한다.
fucntion 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

8.4 서브 클래스의 constructor

  • 클래스에 constructor를 생략하면 비어있는 constructor가 암묵적으로 정의된다
  • 만약 수퍼클래스 서브클래스 모두 constructor가 없다면?
class Base {}
class Derived extends Base {}
  • 위 예제는 암묵적으로 다음과 같이 constructor가 정의된다
class Base {
  constructor() {}
}
class Derived extends Base {
  constructor(...args) { super(...args); }
}

const derived = new Derived();
console.log(derived); // Derived {}
  • 결국은 빈 객체만 생성된다. 왠지 당연한 얘길하고 있는 것 같은데..🤐

8.5 super 키워드

  • super 키워드는 함수처럼 호출할 수 있고, this와 같이 식별자처럼 참조할 수 있는 특수한 키워드이다.

super의 동작

  • 호출 : super 클래스의 constructor를 호출한다.
  • 참조 : super클래스의 메서드를 호출할 수 있다.

super 호출

  • super 클래스의 constructor를 호출
// 수퍼클래스
class Base{
  constructor(a,b) {
    this.a = a;
    this.b = b;
  }
}

//서브클래스
class Derived extends Base{
  //다음과 같이 암묵적으로 constructor가 정의된다.
  // constructor(...args) { super(...args); }
  // 따라서 다음과 같은 생성자가 정의된다
  // constructor(a,b)
  //   super(a,b);
  //   this.c = c;
  //}
}

const derived = new Dervied(1,2,3);
console.log(derived); // Derived {a: 1, b: 2, c: 3}

super 호출 시 주의 사항
1. 서브클래스에서 constructor를 생략하지 않은 경우, 서브클래스의 constructor에서는 반드시 super를 호출해야 한다.
2. 서브클래스의 constructor에서 super를 호출하기 전에는 this를 참조할 수 없다.
3. super는 반드시 서브클래스의 constructor에만 호출한다. 서브 클래스가 아닌 클래스의 constructor나 함수에서 super를 호출하면 에러가 발생한다.

super 참조

  • 메서드 내에서 super를 참조하면 수퍼클래스의 메서드를 호출 할 수 있다.
  1. 서브 클래스의 프로토타입 메서드 내에서 super.sayHi는 수퍼클래스의 프로토타입 메서드 sayHi를 가리킨다.
//수퍼클래스
class Base {
  construcotor(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('Lee');
console.log(derived.sayHi()); //Hi! Lee. how are you doing?
  1. 서브클래스의 정적 메서드 내에서는 super.sayHi는 수퍼클래스의 정적 메서드sayHi를 가리킨다.
//수퍼클래스
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?

8.6 상속 클래스의 인스턴스 생성과정

인스턴스 생성 과정
1. 서브클래스의 super호출
2. 수퍼클래스의 인스턴스 생성과 this바인딩
3. 수퍼클래스의 인스턴스 초기화
4. 서브클래스 constructor로의 복귀와 this바인딩
5. 서브클래스의 인스턴스 초기화
6. 인스턴스 반환

//수퍼클래스
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 extneds Rectangle {
  constructor(width, height, color) {
    super(width, height);
    this.color = colorl
  }
  
  //메서드 오버라이딩
  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

8.7 표준 빌트인 생성자 함수 확장

  • extends 키워드는 [[Construct]] 내부 메서드를 갖는 함수 객체에 사용할 수 있다.
  • String, Number, Array 등의 표준 빌트인 객체도 가능
// Array 생성자 함수를 상속받아 확장
class MyArray extends Array {
  static get [Symbol.species]() { return Array; }
  
  // 중복된 배열 요소를 제거하고 반환: [1,1,2,3] => [1,2,3]
  uniq() {
    return this.filter((v, i , self) => self.indexOf(v) === i);
  }
  // 모든 배열 요소의 평균을 구한다: [1,2,3] => 2
  average() {
    return this.reduce((pre, cur) => pre + cur, 0 ) / this.length;
  }
}

const myArray = new MyArray(1,1,2,3);
console.log(myArray); // MyArray(4) [1,1,2,3]

// // MyArray.prototype.uniq 호출
console.log(myArray.uniq()); // MyArray(3) [1,2,3]

// MyArray.prototype.average 호출
console.log(myArray.average()); // 1.75

// 주의할 점. Array.prototype 메서드 중 map, filter와 같은 새로운 배열을 반환하는 메서드는 MyArray 클래스의 인스턴스를 반환한다.
conosle.log(myArray.filter(v => v % 2) instanceof MyArray); // true

// 왜 그래야만 하냐면, 만약 filter가 Array를 반환하면, uniq(), average() 함수와 메서드 체이닝이 불가능할 것.
// 메서드 체이닝
// [1,1,2,3] => [1,1,3] => [1,3] => 2
console.log(myArray.filter(v => v % 2).uniq().average()); // 2

// 만약  MyArray가 아닌, Array가 생성한 인스턴스를 반환하고 싶다면, 다음 코드를 클래스 안에 추가할 것. 단, 메서드 체이닝은 포기해야 한다.
static get [Symbol.species]() { return Array; ]

0개의 댓글