클래스의 인스턴스 생성
클래스의 인스턴스 생성 과정
new 연산자와 함께 클래스를 호출하면 클래스의 내부 메서드 [[Construct]]가 호출된다.
1. 인스턴스 생성과 this 바인딩
constructor의 내부 코드가 실행되기에 앞서 암묵적으로 빈 객체가 생성된다.
이때 클래스가 생성한 인스턴스의 프로토타입으로 클래스의 prototype 프로퍼티가 가리키는 객체가 설정된다.
암묵적으로 생성된 빈 객체(인스턴스)는 this에 바인딩된다.
따라서 constructor 내부의 this는 클래스가 생성한 인스턴스를 가리킨다.
2. 인스턴스 초기화
constructor의 내부 코드가 실행되어 this에 바인딩되어 있는 인스턴스를 초기화한다.
this에 바인딩 되어 있는 인스턴스에 프로퍼티를 추가하고 constructor가 인수로 전달받은 초기값으로 인스턴스의 프로퍼티 값을 초기화 한다.
3. 인스턴스 반환
클래스의 모든 처리가 끝나면 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
class Person{
//생성자
consturctor(name){
//1.암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
console.log(this); //Person{}
console.log(Object.getPrototypeOf(this) === Person.prototype);
//2. this에 바인딩되어 있는 인스턴스를 초기화 한다.
this.name = name;
//3. 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
}
프로퍼티
인스턴스 프로퍼티는 consturctor 내부에서 정의해야 한다.
class Person {
constructor(name){
this.name = name;
}
}
const me = new Person('Lee');
console.log(me);
constructor 내부에서 this에 추가한 프로퍼티는 언제나 클래스가 생성한 인스턴스의 프로퍼티가 된다.
ES6의 클래스는 private, public 키워드와 같은 접근 제한자를 지원하지 않는다. 언제나 public 하다.
접근자 프로퍼티는 자체적으로 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 사용하는 접근자 함수로 구성된 프로퍼티다.
//객체 리터럴
const person = {
//데이터 프로퍼티
firstName : 'sh',
lastName : 'Lee',
//getter 함수
get fullName(){
return `${this.firstName} ${this.lastName}`;
},
//setter 함수
set fullName(name){
[this.firstName, this.lastName] = name.split(' ');
}
}
//데이터 프로퍼티를 통한 프로퍼티 값의 참조
console.log(`${person.firstName} ${person.lastName}`);
//접근자 프로퍼티를 통한 프로퍼티 값의 저장
person.fullName = 'babo Lee';
console.log(person);
//접근자 프로퍼티를 통한 값의 참조
console.log(person.fullName);
//클래스로 표현
class Person{
constructor(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
get fullName(){
return `${this.firstName} ${this.lastName}`;
}
set fullName(name){
[this.firstName, this.lastName] = name.split(' ');
}
}
const me = new Person('sh', 'Lee');
//데이터 프로퍼티를 통한 프로퍼티 값의 참조
console.log(`${person.firstName} ${person.lastName}`);
//접근자 프로퍼티를 통한 프로퍼티 값의 저장
me.fullName = 'babo Lee';
console.log(me);
//접근자 프로퍼티를 통한 값의 참조
console.log(me.fullName);
getter 는 반드시 무언가를 반환해야 하고 setter 는 반드시 매개변수가 있어야 한다.
클래스의 메서드는 기본적으로 프로토타입 메서드가 된다.
따라서 클래스의 접근자 프로퍼티 또한 인스턴스 프로퍼티가 아닌 프로토타입의 프로퍼티가 된다.
*모던 자바스크립트 DeepDive 참조