javascript class(2)

지난번 정리한 내용에 클래스가 만들어졌을때의 순서를 한번 정리해보았다.

클래스가 하는일

class User {…} 문법 구조가 진짜 하는 일의 순서를

  1. User라는 이름을 가진 함수생성.
  2. 생성자 메서드 constructor에서 작성
  3. 생성자 메서드가 없으면 본문이 비워진 채로 함수가 만들어짐
  4. getFullName 같은 클래스 내에서 정의한 메서드를 User.prototype에 저장
  5. new User를 호출해 객체를 만들고, 객체의 메서드를 호출
  6. 함수의 prototype 프로퍼티에서 설명한 것처럼 메서드를 prototype 프로퍼티를 통해 가져옵니다.
    이 과정이 있기 때문에 객체에서 클래스 메서드에 접근할 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class User {
constructor(name) { this.name = name; }
getFullName(){
return `${this.firstName} ${this.lastName}`
}
}

// 클래스는 함수입니다.
alert(typeof User); // function

// 정확히는 생성자 메서드와 동일합니다.
alert(User === User.prototype.constructor); // true

// 클래스 내부에서 정의한 메서드는 User.prototype에 저장됩니다.
alert(User.prototype.sayHi); // alert(this.name);

// 현재 프로토타입에는 메서드가 두 개입니다.
alert(Object.getOwnPropertyNames(User.prototype)); // constructor, getFullName