JS DeepDive - Class

이상철·2023년 5월 1일
0

JS - DeepDive

목록 보기
4/8
post-thumbnail

Class

클래스는 생성자 함수와 매우 유사하게 동작하지만 다음과 같이 몇 가지 차이가 있다.

  1. 클래스를 new 연산자 없이 호출하면 에러가 발생합니다.
  2. 클래스는 상속을 지원하는 extends와 super 키워드를 제공한다.
  3. 클래스는 호이스팅이 발생하지 않는 것처럼 동작한다.
  4. 클래스 내의 모든 코드에는 암묵적으로 strict모드가 지정되어 실행한다.
  5. 클래스의 contructor, 프로토타입 메서드, 정적 메서드는 모두 프로퍼티 어트리뷰트,[[Enumerable]] 값이 false다. 다시 말해, 열거되지 않는다.

⇒ 클래스는 프로토타입 기반 객체 생성 패턴의 단순한 문법적 설탕이라고 보기보다는 새로운 객체 생성 매커니즘으로 보는 것이 좀 더 합당하다.

클래스 정의

// 클래스는 class 키워드를 사용하여 정의함. 클래스 이름은 파스칼 케이스를 사용하는 것이 일반적이다.
class Person {};

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

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

⇒ 좀 더 자세히 말하면 클래스는 함수다. 따라서 클래스는 값처럼 사용할 수 있는 일급 객체이다.

클래스 몸체에는 0개 이상의 메서드만 정의할 수 있다. 클래스 몸체에서 정의할 수 있는 메서드는 constructor(생성자), 프로토타입 메서드, 정적 메서드 3가지 이다.

class Person {
// 생성자
	constructor (name) {
	// 인스턴스 생성 및 초기화
		this.name = name; // name 프로퍼티는 public이다.			
	}
	
	// 프로토 타입 메서드
	sayHi() {
		console.log(`Hello World My name is ${this.name}`);
	}
	
	// 정적 메서드
	static sayHello() {
		console.log("Hello World")
	}
}

// 인스턴스 생성
const me = new Person("Lee");

// 인스턴스의 프로퍼티 참조
console.log(me.name); // Lee

// 프로토 타입 메서드 호출
me.sayHi(); // Hello World My name is Lee

// 정적 메서드 호출
Person.sayHello() // Hello World

클래스의 호이스팅.

클래스는 함수로 평가된다.

class Person {};

console.log(typeof Person) // function

클래스 선언문으로 정의한 클래스는 함수 선언문과 같이 소스 코드 평가 과정, 즉 런타임 이전에 
먼저 평가되어 함수 객체를 생성한다.
=> 이때 클래스가 평가되어 생성된 함수 객체는 생성자 함수로서 호출할 수 있는 함수 즉, constructor다., 클래스는 클래스 정의 이전에 참조할 수 없다. 

console.log(Person2) // Uncaught ReferenceError: Person2 is not defined
class Person2 {};

클래스 선언문은 마치 호이스팅이 발생하지 않는 것처럼 보이나 그렇지 않다.

const Person = "";
{
	// 호이스팅이 발생하지 않는다면, ""이 출력되어야 함.
	console.log(Person); // caught SyntaxError: Identifier 'Person' has already been declared

	class Person{};
}

클래스는 선언문 이전에 일시적 사각지대 TDZ에 빠지기 때문에 호이스팅이 발생하지 않는 것처럼 동작.

인스턴스 생성

클래스는 생성자 함수이며, new 연산자와 함께 호출되어 인스턴스를 생성한다.

class Person {}

// 인스턴스 생성
const me = new Person();
console.log(me) // Person{}
=> 클래스는 인스턴스를 생성하는 것이 유일한 존재 이유이므로 반드시 new 연산자와 함께 호출해야 한다.

const me2 = Person();
console.log(me2) // Uncaught TypeError: Class constructor Person cannot be invoked without 'new'

/* 
	클래스 표현식으로 정의된 클래스의 경우 식별자를 사용해 인스턴스를 생성하지 않고, 
	기명 클래스 표현식의 클래스 이름을 사용해 인스턴스를 생성하면 에러 발생
*/

const Person3 = class MyClass{};

const me3 = new Person3();

console.log(MyClass) // Uncaught ReferenceError: MyClass is not defined

const you = new MyClass(); // Uncaught ReferenceError: MyClass is not defined

=> 이는 기명함수 표현식과 마친가지로 클래스 표현식에서 사용한 클래스 이름은 
외부코드에서 접근 불가능하기 때문

메서드

클래스 몸체에는 0개 이상의 메서드만 정의할 수 있다. 클래스 몸체에서 정의할 수 있는 메서드는 constructor(생성자), 프로토타입 메서드, 정적 메서드 3가지 이다.

constructor

constructor는 인스턴스를 생성하고 초기화하기 위한 특수한 매서드.

class Person2 {
	// 생성자
	constructor(name) {
		// 인스턴스 생성 및 초기화
		this.name = name;
	}
}

앞에서 살펴보았듯, 클래스는 인스턴스를 생성하기 위한 생성자 함수다.

const me = new Person2("Lee");
console.log(me)

스크린샷 2023-04-18 오전 5.18.52.png

Person 클래스의 constructor 내부에서 this에 추가한 name 프로퍼티가 클래스가 생성한 인스턴스의 프로퍼티로 추가된 것을 확인할 수가 있다. 즉, 생성자 함수와 마찬가지로 constructor 내부에서 this에 추가한 프로퍼티는 인스턴스 프로퍼티가 된다. constructor 내부의 this는 생성자 함수와 마찬가지로 클래스가 생성한 인스턴스를 가리킨다.

constructor의 특징

  1. constructor는 클래스 내에 최대 한 개만 존재할 수 있다.
  2. constructor는 생략 가능하다.
  3. constructor를 생략하면 클래스에 다음과 같이 빈 constructor가 암묵적으로 정의된다.
  4. 프로퍼티가 추가되어 초기화 된 인스턴스를 생성하려면, constructor 내부에서 this에 인스턴스 프로퍼티를 추가한다.
class Person {
    constructor (name,age) {
        this.name = name;
        this.age = age;
        this.gender = "male"
        this.language = "ko"
    }
}

const i = new Person("lee",28)
const j = new Person("kim",30)
const k = new Person("park",23)

i => Person {name: 'lee', age: 28, gender: 'male', language: 'ko'}
j => Person {name: 'kim', age: 30, gender: 'male', language: 'ko'}
k => Person {name: 'park', age: 23, gender: 'male', language: 'ko'}

인스턴스를 생성할 때, 클래스 외부에서 인스턴스 프로퍼티의 초기값을 전달하려면 다음과 같이 constructor의
매개변수를 선언하고 인스턴스를 생성할 때 초기값을 전달한다. 이때 초기값은 constructor의 매개변수에게
전달된다.

위 처럼, constructor 내에서는 인스턴스의 생성과 동시에 인스턴스 프로퍼티 추가를 통해 인스턴스의 
초기화를 실행한다. 따라서 인스턴스를 초기화하려면 constructor를 생략해서는 안된다.
  1. constructor는 별도의 반환문을 갖지 않아야한다. new 연산자와 함께 클래스가 호출되면 생성자 함수와 동일하게 암묵적으로는 this, 즉 인스턴스를 반환하기 때문이다. 만약 this가 아닌 다른 객체를 명시적으로 반환하면 this, 즉 인스턴스가 반환되지 못하고 return 문에 명시한 객체가 반환된다.
class Person {
	constructor (name) {
		this.name = name;

		// 명시적으로 객체를 반환하면 암묵적인 this 반환이 무시된다.
		return {};
	}
}

const me = new Person("lee");
console.log(me) // {}

하지만, 명시적으로 원시값을 반환하면 원시값 반환은 무시되고 암묵적으로 this가 반환된다.

class Person2 {
	constructor (name) {
		this.name = name;

		// 명시적으로 객체를 반환하면 암묵적인 this 반환이 무시된다.
		return 100;
	}
}

const me = new Person2("lee");
console.log(me) // Person2 {name: 'lee'}

이처럼 constructor 내부에서 명시적으로 this가 아닌 다른 값을 반환하는 것은 클래스의 기본 동작을
훼손한다. 따라서 constructor 내부에서 return 문을 반드시 생략해야한다.

프로토타입 메서드

생성자 함수를 사용하여 인스턴스를 생성해야 하는 경우 프로토타입 메서드를 생성하기 위해서는 다음과 같이 명시적으로 프로토타입에 메서드를 추가해야한다.

function Person(name) {
	this.name = name;
}

Person.prototype.sayHi = function () {
	console.log(`Hello World I'm ${this.name}`);
}

const me = new Person("lee");
me.sayHi() // Hello World I'm lee

클래스 몸체에서 정의한 메서드는 생성자 함수에 의한 객체 생성 방식과는 다르게 클래스의 prototype 프로퍼티에 메서드를 추가하지 않아도 기본적으로 프로토타입 메서드가 된다.

class Person {
	constructor(name) {
			this.name = name;
	}
	sayHi () {
		console.log(`Hello World i'm ${this.name}`)
	}
}

const me = new Person("kim");
console.log(me) // Person {name: 'kim'}
me.sayHi() // Hello World i'm kim

생성자 함수와 마찬가지로 클래스가 생성한 인스턴스는 프로토타입 체인의 일원이 된다.

클래스 몸체에서 정의한 메서드는 인스턴스의 프로토타입에 존재하는 프로토타입 메서드가 된다. 인스턴스는 프로토타입 메서드를 상속받아 사용할 수 있다.

프로토타입 체인은 기존의 모든 객체 생성 방식 (객체 리터럴, 생성자 함수, Object.create 메서드 등) 뿐만 아니라 클래스에 의해 생성된 인스턴스에도 동일하게 적용된다. 생성자 함수의 역할을 클래스가 할 뿐이다.

결국 클래스는 생성자 함수와 같이 인스턴스를 생성하는 생성자 함수라고 볼 수 있다. 다시 말해, 클래스는 생성자 함수와 마찬가지로 프로토타입 기반의 객체 생성 메커니즘이다.

정적 메서드

정적 메서드는 인스턴스를 생성하지 않아도 호출할 수 있는 메서드를 말한다.

// 생성자 함수
function Person(name) {
	this.name = name
}

// 정적 메서드
Person.sayHi = function () {
	console.log("Hello world")
}

// 정적 메서드 호출
Person.sayHi(); // Hello world

// 클래스
// 클래스에서는 메서드에 static 키워드를 붙이면 정적 메서드(클래스 메서드)가 된다.

class Person2 {
	constructor(name) {
		this,name = name;
	}

	// 정적 메서드
	static sayHi() {
		console.log(`Hello World`)
	}
}

Person2.sayHi() // Hello World

const me = new Person2("park")
me.sayHi(); // Uncaught TypeError: me.sayHi is not a function

이 처럼 정적 메서드는 클래스에 바인딩된 메서드가 된다. 클래스는 함수 객체로 평가되므로 자신의 프로퍼티/메서드를 소유할 수 있다. 클래스는 클래스 정의(클래스 선언문이나 클래스 표현식)가 평가되는 시점에 함수 객체가 되므로 인스턴스와 달리 별다른 생성 과정이 필요하다. 따라서 정적 메서드는 클래스 정의 이후 인스턴스를 생성하지 않아도 호출할 수 있다.

정적 메서드는 프로토타입 메서드 처럼 인스턴스로 호출하지 않고 클래스로 호출한다.

정적 메서드는 인스턴스로 호출 할 수 없다. 정적 메서드가 바인딩된 클래스는 인스탄스의 프로토타입 체인상에 존재하지 않기 때문이다. 다시 말해, 인스턴스의 프로토타입 체인 상에는 클래스가 존재하지 않기 때문에 인스턴스로 클래스의 메서드를 상속받을 수 밖에 없다.

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

  1. 정적 메서드와 프로토타입 메서드는 자신이 속해 있는 프로토타입 체인이 다르다.
  2. 정적 메서드는 클래스로 호출하고 프로토타입 메서드는 인스턴스로 호출한다.
  3. 정적 메서드는 인스턴스 프로퍼티를 참조할 수 없지만, 프로토타입 메서드는 인스턴스 프로퍼티를 참조할 수 있다.
// 예제 코드

class Square {
	static area(width, height) {
		return width * height
	}
}

console.log(Square.area(10,10)) // 100

정적 메서드 area는 2개의 인수를 전달받아 면적을 계산한다. 이때 정적 메서드 area는 인스턴스 프로퍼티를
참조하지 않는다. 만약 인스턴스 프로퍼티를 참조해야 한다면 정적 메서드 대신 프로토타입 메서드를 사용해야함.

class Square2 {
	constructor(width, height) {
		this.width = width;
		this.height = height;
	}

	// 프로토타입 메서드
	area() {
		return this.width * this.height
	}
}

const square = new Square2(10,10);
console.log(square.area()); // 100

프로토타입 메서드는 인스턴스로 호출해야 하므로 프로토타입 메서드 내부의 this는 프로토타입 메서드를 호출한 인스턴스를 가르킨다.

위 예제의 경우 square 객체로 프로토타입 메서드 area를 호출했기 때문에 area 내부의 this는 square객체를 가르킨다.

정적 메서드는 클래스로 호출해야 하므로 정적 메서드 내부의 this는 인스턴스가 아닌 클래스를 가르킨다. 즉, 프로토 타입 메서드와 정적 메서드 내부의 this 바인딩이 다르다.

따라서 메서드 내부에서 인스턴스 프로퍼티를 참조할 필요가 있다면, this를 사용해야 하며, 이러한 경우 프로토타입 메서드로 정의해야한다.

하지만 메서드 내부에서 인스턴스 프로퍼티를 참조해야할 필요가 없다면, this를 사용하지 않게 된다.

물론 메서드 내부에서 this를 사용하지 않더라도 프로토타입 메서드로 정의할 수 있다. 하지만 반드시 인스턴스를 생성한 다음 인스턴스로 호출해야하기 하므로 this를 사용하지 않는 메서드는 정적 메서드로 정의 하는 것이 좋다.

정적 메서드를 모아 놓으면 이름 충돌 가능성을 줄여 주고 관련 함수들을 구조화할 수 있는 효과가 있다.

정적 메서드는 애플리케이션 전역에서 사용할 유틸리티 함수를 전역 함수로 정의하지 않고 메서드로 구조화할 때 유용하다.

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

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

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

    1. 인스턴스 생성과 this 바인딩

      new 연산자와 함께 클래스를 호출하면, constructor의 내부 코드가 실행되기에 앞서 암묵적으로 빈 객체가 생성된다. 이 빈 객체가 인스턴스.

      이때 클래스가 생성한 인스턴스의 프로토타입으로 클래스의 prototype 프로퍼티가 가리키는 객체가 설정된다.

      위에서 암묵적으로 생성된 빈 객체, 즉 인스턴스는 this에 바인딩 된다.

      따라서, contractor 내부의 this는 클래스가 생성한 인스턴스를 가리킨다.

    1. 인스턴스 초기화

      constructor의 내부 코드가 실행되어 this에 바인딩되어 있는 인스턴스를 초기화한다.

      즉, this에 바인딩 되어 있는 인스턴스에 프로퍼티를 추가하고 constructor가 인수로 전달받은 초기값으로 인스턴스의 프로퍼티 값을 초기화한다. 만약 constructor가 생략되었다면 이 과정도 생략

    1. 인스턴스 반환

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

      class Person {
      	constructor(name) {
      		// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩 된다.
      		console.log(this) // Person{}
      		console.log(Object.getPrototypeOf(this) === Person.prototype);//true	
      	
      		// 2. this에 바인딩 되어 있는 인스턴스를 초기화한다.
      		this.name = name;	
      	
      		// 3. 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
      	}
      }

접근자 프로퍼티

class Person2 {
    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 me2 = new Person2("ian","lee");

// 데이터 프로퍼티를 통한 프로퍼티 값의 참조.
// console.log(`${me2.firstName}` `${me2.lastName}`); // ian lee

// 접근자 프로퍼티를 통한 프로퍼티 값의 저장
// 접근자 프로퍼티 fullName에 값을 저장하면, setter함수가 호출된다.
me.fullName = "sangcheol Lee";
console.log(me2) // {firstName : "sangcheol", lastName: "Lee"}

// 접근자 프로퍼티를 통한 프로퍼티 값의 참조.
// 접근자 프로퍼티 fullName에 접근하면 getter 함수가 호출된다.
console.log(me2.fullName) // sangcheol Lee

// fullName은 접근자 프로퍼티이다.
// 접근자 프로퍼티는 get,set enumerable, configurable 프로퍼티 어트리뷰트를 갖는다.
console.log(Object.getOwnPropertyDescriptor(Person2.prototype, "fullName"));

접근자 프로퍼티는 자체적으로 값을 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 사용하는 접근자 함수, 즉 getter 함수와 setter함수로 구성되어 있다.

getter는 인스턴스 프로퍼티에 접근할 때마다 프로퍼티 값을 조작하거나 별도의 행위가 필요할 때 사용한다.

getter는 메서드 이름 앞에 get 키워드를 사용해 정의한다.

setter는 인스턴스 프로퍼티에 값을 할당할 때마다 프로퍼티 값을 조작하거나 별도의 행위가 필요할 때 사용한다.

setter는 메서드 이름 앞에 set키워드를 사용해 정의한다.

getter와 setter 이름은 인스턴스 프로퍼티처럼 사용된다.

getter는 이름 그대로 무언가를 취득할 때 사용하므로 반드시 무언가를 반환해야 하고

setter는 무언가를 프로퍼티에 할당해야 할 떄 사용하므로 반드시 매개변수가 있어야 한다. setter는 단 하나의 값만 할당 받기 때문에 단 하나의 매개변수만 선언할 수 있다.

상속에 의한 클래스 확장

상속에 의한 클래스 확장은 기존 클래스를 상속받아 새로운 클래스를 확장하여 정의하는 것

// 수퍼 클래스
class Animal {
    constructor(age, weight) {
        this.age = age
        this.weight = weight
    }

eat() { return "eat"}

move() {return "move"}
}

// 서브 클래스
class Bird extends Animal {
    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

=> 이처럼 상속에 의한 클래스 확장은 코드 재사용 관점에서 매우 유용하다.

extends 키워드.

  • 상속을 통해 확장된 클래스를 서브클래스라 부르고 서브클래스에게 상속된 클래스를 수퍼클래스라고 함
  • extends 키워드의 역할은 수퍼 클래스와 서브클래스 간의 상속 관계를 설정하는 것이다. 클래스도 프로토타입을 통해 상속 관계를 구현함.

동적 상속

// extends 키워드는 클래스 뿐만 아니라 생성자 함수를 상속받아 클래스를 확장할 수 있다.
// 단, extends 키워드앞에는 반드시 클래스가 와야한다.

function Base(a){
	this.a = a;
}

// 생성자 함수를 상속받는 서브클래스

class Derived extends Base{}

const derived = new Derived(1)
console.log(devived) // Derived {a:1}

// extends 키워드 다음에는 클래스 뿐만 아니라 [[cConstruct]] 내부 메서드를 갖는 
// 함수 객체로 평가될 수 있는 모든 표현식을 사용할 수 있다.
// 이를 통해 동적으로 상속받을 대상을 결정할 수 있다.

function Base1() {}

class Base2 {}

let condition = true;

class Devided extends (condition ? Base1 : Base2) {}

const devide = new Devided()

console.log(devide); // Devided {}

console.log(devide instanceof Base1) true
console.log(devide instanceof Base2) false

서브클래스의 constructor

  • 서브 클래스에서 constructor를 생략하면 클래스에 다음과 같은 constructor가 암묵적으로 정의된다.args는 new 연산자와 함께 클래스를 호출할 때 전달한 인수의 리스트다.
  • super()는 수퍼클래스의 constructor를 호출하여 인스턴스를 생성한다.
class Base {}

class Child extends Base {}

// 위에서 선언한 클래스는 암묵적으로 아래와 같이 변경됨.

class Base {
	constructor() {}
}

class Child extends Base {
	constructor(...args) {super(...args);}
}

const child = new Child();
console.log(child)

위 예제와 같이 수퍼클래스와 서브클래스 모두 constructor를 생략하면 빈 객체가 생성된다. 프로퍼티를 소유하는 인스턴스를 생성하려면 constructor 내부에서 인스턴스에 프로퍼티를 추가해야한다.

super 키워드

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

  • super를 호출하면 수퍼클래스의 constructor(super-constructor)를 호출한다.

  • super를 참조하면 수퍼클래스의 메서드를 호출할 수 있다.

  • super 호출

    super를 호출하면 수퍼클래스의 constructor(super-constructor)를 호출한다.

    class Base {
    	constructor(a,b) {
    		this.a = a;
    		this.b = b;
    	}
    }
    
    class Child extends Base{
    	// 암묵적으로 constructor 정의
    	// constructor(...args){super(...args)}
    }
    
    const child = new Child(5,6) // Child {a: 5, b: 6}

    아래 예제와 같이 수퍼 클래스에서 추가한 프로퍼티와 서브클래스에서 추가한 프로퍼티를 갖는 인스턴스를 생성한다면 서브클래스의 constructor를 생략할 수 없다. 이때 new 연산자와 함께 서브클래스를 호출하면서 전달한 인수중에서 수퍼클래스의 constructor에 전달할 필요가 있는 인수는 서브클래스의 constructor에서 호출하는 super를 통해 전달한다.

    class Base {
    	constructor(a,b) { // 4
    		this.a = a;
    		this.b = b; 
    	}
    }
    
    class Child extends Base {
    	constructor(a,b,c) { // 2
    		super(a,b) // 3
    		this.c = c;
    	}
    }
    
    const child = new Child(1,2,3); // 1
    
    console.log(child) // Child {a: 1, b: 2, c: 3}
    
    1. new 연산자와 함께 Child클래스를 호출하면서 전달한 인수 1,2,32. Child 클래스의 constructor에 전달 되고
    3. super호출을 통해
    4. Base 클래스의 constructor에 일부가 전달된다.
    
    => 이처럼 인스턴스 초기화를 위해 전달한 인수는 수퍼클래스와 서브클래스에 배분되고 상속 관계의
     두 클래스는 서로 협력하여 인스턴스를 생성한다.
    • super 호출 시 주의사항
      1. 서브 클래스에서 constructor를 생략하지 않은 경우 서브 클래스의 constructor에서는
      반드시 super를 호출해야 한다.
      
      class Base {}
      
      class Child extends Base {
      	constructor() {
      		console.log("call")
      	}
      }
      
      const child = new Child();
      // error log
      // caught ReferenceError: Must call super constructor in derived class 
      // before accessing 'this' or returning from derived constructor
      
      2. 서브 클래스의 constructor에서 super를 호출하기 전에는 this를 참조할 수 없다.
      
      class Base {}
      
      class Child extends Base {
      	constructor() {
      		this.a = 1;
      		super();
      	}
      }
      
      const child = new Child(1);
      // error log
      // caught ReferenceError: Must call super constructor in derived class 
      // before accessing 'this' or returning from derived constructor
      
      3. super는 반드시 서브클래스의 constructor에서만 호출한다. 서버클래스가 아닌 클래스의
      constructor나 함수에서 super를 호출하면 에러가 발생한다.
      
      class Base {
      	constructor() {
      		super();
      	}
      }
      
      function Foo(){
      	super()
      }
      
      // error log
      // caught SyntaxError: 'super' keyword unexpected here
  • super 참조

    • 메서드 내에서 super를 참조하면 수퍼 클래스의 메서드를 호출할 수 있다.
      1. 서브 클래스의 프로토타입 메서드 내에서 super.sayHi는 수퍼클래스의 프로토타입 메서드
      sayHi를 가르킨다.
      
      class Base {
      	constructor(name) {
      		this.name = name;
      	}
      	sayHi() {
      		return `안녕 내 이름은 ${this.name} 이야 ~!`
      	}
      }
      
      class Child extends Base {
      	sayHi() {
      		return `${super.sayHi()}. 잘 지내니 ?`
      	}
      }
      
      const child = new Child("이상철");
      
      console.log(child.sayHi()) // 안녕 내 이름은 이상철 이야 ~!. 잘 지내니 ?
      • 서브 클래스의 정적 메서드 내에서 super.sayHi는 수퍼클래스의 정적 메서드 sayHi를 나타낸다.
        class Base {
        	static sayHi() {
        		return "Hello"	
        	}
        }
        
        class Child extends Base {
        	static sayHi() {
        		return `${super.sayHi()} my name is sangcheol`
        	}
        }
        
        console.log(Child.sayHi())

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

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 colorRec = new ColorRectangle(10,10,"Red");
console.log("colorRec",colorRec) // {width: 10, height: 10, color: 'Red'}

console.log(Number(colorRec.getArea())) // 100
console.log(colorRec.toString()) // width = 10, height = 10 color = Red
  1. 서브 클래스의 super 호출

수퍼 클래스와 서브클래스는 new 연산자와 함께 호출되었을 때 동작이 구분됩니다.

다른 클래스를 상속받지 않는 클래스(그리고 생성자 함수)는 new 연산자와 함께 호출되었을 때 암묵적으로 빈 객체, 즉 인스턴스를 생성하고 이를 this에 바인딩한다.

서브클래스는 자신이 직접 인스턴스를 생성하지 않고 수퍼클래스에게 인스턴스 생성을 위임한다. 이것이 바로 서브클래스의 constructor에서 반드시 super를 호출해야 하는 이유이다.

서브 클래스가 new 연산자와 함께 호출되면 서브 클래스는constructor 내부의 super 키워드가 함수처럼 호출된다. super가 호출되면 수퍼클래스의 constructor(super-constructor)가 호출된다. 좀 더 정확히 말하자면 수퍼클래스가 평가되어 생성된 함수 객체의 코드가 실행 되기 시작한다.

만약 서브 클래스 constructor 내부에 super 호출이 없으면 에러가 발생한다. 실제로 인스턴스를 생성하는 주체는 수퍼클래스 이므로 수퍼클래스의 constructor를 호출하는 super가 호출되지 않으면 인스턴스를 생성할 수 없기 때문이다.

  1. 수퍼 클래스의 인스턴스 생성과 this 바인딩.

    수퍼클래스의 constructor 내부의 코드가 실행되기 이전에 암묵적으로 빈 객체를 생성한다. 이 빈 객체가 바로 (아직 생성되지는 않았지만) 클래스가 생성한 인스턴스다 그리고 암묵적으로 생성된 빈 객체, 즉 인스턴스는 this에 바인딩된다. 따라스 수퍼클래스의 constructor 내부의 this는 생성된 인스턴스를 가르킨다.

    class Rectangle {
    	constructor(width, height) {
    		this.width = width;
    		this.height = height;
        console.log(this) //ColorRactengle {}
    		console.log(new.target) // ColorRactengle
    	}
    
    	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 colorRec = new ColorRectangle(10,10,"Red");
    console.log("colorRec",colorRec) // {width: 10, height: 10, color: 'Red'}
    
    console.log(Number(colorRec.getArea())) // 100
    console.log(colorRec.toString()) // width = 10, height = 10 color = Red

    ⇒ 콘솔 결과.

    스크린샷 2023-04-21 오전 5.05.15.png

    이때 인스턴스는 수퍼클래스가 생성한 것이다. 하지만 new 연산자와 함께 호출된 클래스가 서브 클래스라는 것이 중요하다. 즉 new 연산자와 함께 호출된 함수를 가리키는 new.target은 서브 클래스를 가리킨다. 따라서 인스턴스는 new.target이 가리키는 서브클래스가 생성한 것으로 처리된다.

    따라서 생성된 인스턴스의 프로토타입은 수퍼클래스의 prototype 프로퍼티가 가리키는 객체 (Rectangle prototype)가 아니라 new.target, 즉 서브클래스의 prototype 프로퍼티가 가르키는 객체(ColorRactengle.prototype)이다

    class Rectangle {
    	constructor(width, height) {
    		// 암묵적으로 빈 객체, 즉 인스턴스가 생성되고 this에 바인딩 된다.
    		this.width = width;
    		this.height = height;
        console.log(this) //ColorRactengle {}
    		console.log(new.target) // ColorRactengle
        console.log(Object.getPrototypeOf(this) === ColorRectangle.prototype) // true
        console.log(this instanceof ColorRectangle) // true
        console.log(this instanceof Rectangle) // true
    	}
    
    	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 colorRec = new ColorRectangle(10,10,"Red");
    console.log("colorRec",colorRec) // {width: 10, height: 10, color: 'Red'}
    
    console.log(Number(colorRec.getArea())) // 100
    console.log(colorRec.toString()) // width = 10, height = 10 color = Red
    1. 수퍼 클래스의 인스턴스 초기화

      수퍼클래스의 contructor가 실행되어 this에 바인딩되어 있는 인스턴스를 초기화한다. 즉, this에 바인딩 되어 있는 인스턴스에 프로퍼티를 추가하고 constructor가 인수로 전달받은 초기값으로 인스턴스의 프로퍼티를 초기화한다.

      class Rectangle {
      	constructor(width, height) {
      		// 암묵적으로 빈 객체, 즉 인스턴스가 생성되고 this에 바인딩 된다.
          console.log(this) //ColorRactengle {}
      		// new 연산자와 함께 호출된 함수, 즉 new.target은 ColorRectangle(서브클래스)이다.
      		console.log(new.target) // ColorRactengle
          console.log(Object.getPrototypeOf(this) === ColorRectangle.prototype) // true
          console.log(this instanceof ColorRectangle) // true
          console.log(this instanceof Rectangle) // true
      		// 인스턴스 초기화
      		this.width = width;
      		this.height = height;
      		
      		console.log(this) // ColorRectangle{width :2, height:4}
      	}
      
      	...
      }

      스크린샷 2023-04-21 오전 5.19.57.png

      1. 서브클래스 constructor로의 복귀와 this 바인딩.

        super 클래스의 호출이 종료되고 제어 흐름이 서브 클래스 constructor로 돌아온다. 이때 super가 반환한 인스턴스가 this에 바인딩된다. 서브클래스는 별도의 인스턴스를 생성하지 않고 super가 반환한 인스턴스를 this에 바인딩하여 그대로 사용한다.

        class ColorRectangle extends Rectangle {
        	constructor (width, height, color) {
        		super(width, height);
        		
        		// super가 반환한 인스턴스가 this에 바인딩 된다.
        		console.log(this) // ColorRectangle{width : 10, height : 10}
        
        		this.color = color;
        	}
        
        	toString() {
        		return super.toString() + ` color = ${this.color}`
        	}
        }

        이 처럼 super가 호출되지 않으면 인스턴스가 생성되지 않으며, this 바인딩도 할 수 없다. 서브클래스의 constructor에서 super를 호출하기 전에는 this를 참조할 수 없는 이유가 바로 이 때문이다.

        따라서 서브클래스 constructor 내부의 인스턴스 초기화는 반드시 super 호출 이후에 처리되어야 한다.

        1. 서브클래스의 인스턴스 초기화

          super호출 이후, 서브 클래스의 constructor에 기술되어 있는 인스턴스 초기화가 실행된다.

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

        2. 인스턴스 반환

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

profile
헤더부터 푸터까지!!!

0개의 댓글