관리 메뉴

진취적 삶

25 클래스 본문

개발 도서/자바스크립트 deepdive

25 클래스

hp0724 2023. 7. 12. 11:39

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

  1. 클래스를 new 연산자 없이 호출하면 에러가 발생 생성자 함수를 new 연산자 없이 호출하면 일반함수 호출
  2. 클래스는 상속 지원 extends 와 super 지원 생성자 함수는 extends 와 super 지원안함
  3. 클래스는 호이스팅이 발생하지 않는것처럼 제공 함수 선언문으로 정의된 생성자 함수는 함수 호이스팅이 ,함수 표현식으로 정의한 생성자 함수는 변수 호이스팅 발생
  4. 클래스 내의 모든 코드에는 암묵적으로 strict mode 실행 생성자 함수는 stride mode 지정하지 않음
  5. 클래스의 constructor ,프로토타입 ,정적 메서드는 모두 Enumerable 열거 되지 않는다.

25.2 클래스 정의

const Person =class{}

클래스를 표현식으로 정의할수 있는것은 클래스 값으로 사용할수 있는 일급 객체라는것을 의미한다.

  • 무명의 리터럴로 생성할수있다. 즉 런타임에 생성이 가능
  • 변수나 자료구조에 저장
  • 함수의 매개변수에 전달
  • 함수의 반환값으로 사용가능

클래스는 함수다 .클래스는 값처럼 사용할수 있는 일급 객체다

클래스 몸체에 정의할수 있는 메서드는 생성자 ,프로토타입 메서드 ,정적메서드 가있다 .

 

class Person {
  constructor(name) {
    //인스턴스 생성및 초기화
    this.name = name;
  }
  //프로토타입 메서드
  sayHi() {
    console.log(`hi my name is ${this.name}`);
  }
  //정적 메서드
  static sayHello() {
    console.log("hello");
  }
}
//인스턴스 생성
const me = new Person("lee");

console.log(me.name); //lee
me.sayHi(); //hi my name is lee
Person.sayHello(); //hello

25.3 클래스 호이스팅

클래스는 함수로 평가

class Person {}
console.log(typeof Person) //function 

클래스 선언문으로 정의한 클래스는 런타임 이전에 평가되어 함수 객체를 생성

클래스가 평가되어 생성된 함수 객체는 생성자 함수로서 호출 할수 있는 함수

즉 constructor다 . 생성자 함수로서 호출할수 있는 함수는 함수 정의가 평가되어 함수 객체를 생성하는 시점에 프로토타입도 더불어 생성된다. 프로토 타입과 생성자 함수는 단독으로 존재할수 없고 언제나 쌍으로 존재한다. 단 클래스는 클래스 이전에 참조할수 없다 .

클래스 선언은 let,const 키워드같이 일시적 사각지대에 빠지기 때문에 호이스팅이 발생하지 않은것처럼 작동한다.

25.4 인스턴스 생성

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

class Person {}
const me = new Person();
console.log(me);

클래스를 가리키는 식별자를 사용해 인스턴스를 생성하지 않고 기명 클래스 표현식의 클래스 이름을 사용해 인스턴스를 생성하면 에러가 발생

25.5 메서드

클래스 몸체에 정의할수 있는 메서드는 생성자 ,프로토타입 메서드 ,정적 메서드가 있다.

25.5.1 constructor

constructor 는 인스턴스를 생성하고 초기화 하기 위한 특수한 메서드다 이름 변경은 불가능

class Person {
	constructor(name) {
		this.name = name ;
	}
}

클래스도 함수 객체의 고유의 프로퍼티를 모두 갖고 있다.

prototype 프로퍼티가 가리키는 프로토타입 객체의 constructor 프로퍼티는 클래스 자신을 가리킨다. 클래스가 인스턴스를 생성하는 생성자 함수라는것을 의미한다. new 연산자와 함께 클래스를 호출하면 클래스는 인스턴스를 생성한다.

constructor 는 메서드로 해석되는것이 아니라 클래스가 평가되어 생성한 함수 객체의 코드의 일부가 된다. 클래스 정의가 평가되면 constructor 의 기술된 동작을 하는 함수 객체가 평가된다.

constructor 는 클래스내에 최대 한개만 존재 가능 생략 가능 생략 할경우 빈객체를 생성

인스턴스를 초기화 할경우 constructor 를 생략해서는 안된다. new 연산자와 함께 클래스가 호출되면 생성자 함수와 동일하게 암묵적으로 this 를 반환하기 때문이다 .

명시적으로 객체를 반환하면 this 반환이 무시된다 . 그러나 명시적으로 원시값을 반환하면 암묵적으로 this 가 반환된다.

25.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();
//Person.prototype의 프로토타입은 Object.prototype 이다
console.log(Object.getPrototypeOf(Person.prototype) === Object.prototype);
console.log(me instanceof Object);
//me 객체의 constructor 는 Person 클래스다
console.log(me.constructor === Person);

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

25.5.3 정적 메서드

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

정적 메서드는 클래스에 바인딩된 메서드가 된다. 클래스는 클래스 정의가 평가되는 시점에 함수 객체가 되므로 인스턴스와 달리 별다른 생성과정이 필요없다 . 따라서 정적 메서드는 클래스 정의 이후 인스턴스를 생성하지 않아도 호출할수 있다 .

인스턴스의 프로토타입 체인상에는 클래스가 존재하지 않기 때문에 인스턴스로 클래스의 메서드를 상속받을수 없다 .

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

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

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

  1. 인스턴스 생성과 this 바인딩 new 연산자와 함께 클래스를 호출하면 constructor 의 내부코드가 실행되깆 전 암묵적으로 빈 객체가 생성된다. 클래스가 생성한 인스턴스의 프로토타입으로 prototype 프로퍼티가 가리키는 객체가 설정된다. 암묵적으로 생성된 빈 객체, 인스턴스는 this에 바인딩 된다.
  2. 인스턴스 초기화 constructor 내부 코드가 실행되어 this 에 바인딩 되어 있는 인스턴스를 초기화한다.
  3. 인스턴스 반환 클래스의 모든 처리가 끝나면 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.

25.7 프로퍼티

25.7.1 인스턴스 프로퍼티

인스턴스 프로퍼티는 constructor 내부에서 정의해야한다.

constructor 내부에서 this에 인스턴스 프로퍼티 추가한다. 인스턴스 프로퍼티가 추가되어 인스턴스가 초기화 된다.

25.7.2 접근자 프로퍼티

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

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

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

class인스

25.7.3 클래스 필드 정의 제안

클래스가 생성할 인스턴스의 프로퍼티를 가리키는 용어

js의 클래스에서 인스턴스 프로퍼티를 선언하고 초기화 할려면 constructor 내부에서 this에 프로퍼티를 추가해야한다.

클래스 기반 객체지향 언어의 this는 언제나 클래스가 생성할 인스턴스를 가리킨다.

그러나 최신 브라우저나 최신node.js는 클래스 몸체에서 클래스 필드 정의를 가능하게 함

인스턴스를 생성할 때 외부 초기값으로 클래스 필드를 초기화할 필요가 있다면 constructor 에서 인스턴스 프로퍼티를 정의 하는 기존 방식을 상용

25.7.4 private 필드 정의 제안

인스턴스를 통해 클래스 외부에서 언제나 참조할수 있다 . 언제나 public이다

private 필드의 선두에는 #을 붙여준다 . 참조할때도 #을 쓰자

class Person {
  #name = "";
  constructor(name) {
    this.#name = name;
  }
}

const me = new Person("lee");
//클래스 외부에서 참조 불가능
console.log(me.#name); //  Private field '#name' must be declared in an enclosing class

private 필드는 반드시 클래스 몸체에 정의해야한다.

접근자 프로퍼티를 통해 간접적으로 접근하는 방법은 유효하다 .

class Person {
  #name = "";
  constructor(name) {
    this.#name = name;
  }
//접근자 프로퍼티 
  get name() {
    return this.#name.trim();
  }
}

const me = new Person(" lee ");
console.log(me.name);

25.7.5 static 필드 정의 제안

class MyMath {
  static PI = 22 / 7;
  //static private 필드 정의
  static #num = 10;
  //static 메서드
  static increment() {
    return ++MyMath.#num;
  }
}

console.log(MyMath.PI);
console.log(MyMath.increment());

25.8 상속에 의한 클래스 확장

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

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

25.8.2 extends 키워드

extends 키워드를 사용하여 사용받을 클래스를 정의한다.

상속에 의해 확장된 클래스를 서브클래스라 부르고, 서브 클래스에게 상속된클래스를 수퍼 클래스라 부른다. 서브클래스를 자식 클래스 ,수퍼클래스를 부모클래스라 부르기도 한다.

extends 키워드는 수퍼클래스와 서브 클래스 간의 상속 관계를 설정

수퍼클래스와 서브클래스는 인스턴스의 프로토타입 체인 뿐만 아니라 클래스 간의 프로토타입 체인도 생성한다.

25.8.3 동적 상속

function Base1() {}
class Base2 {}

let condition = false;

class Derived extends (condition ? Base1 : Base2) {}
const derived = new Derived();
console.log(derived);

console.log(derived instanceof Base1); //false
console.log(derived instanceof Base2); //true

25.8.4 서브클래스의 constructor

수퍼 클래스와 서브 클래스 모두 constructor를 생략하면 빈 객체가 생성된다.

프로퍼티를 소유하는 인스터스를 생성하려면 constructor 내부에서 인스턴스에 프로퍼티를 추가해야한다.

25.8.5 super 키워드

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

  • super 클래스를 호출하면 constructor(부모의 생성자) 를 호출한다.
  • super 를 참조하면 수퍼클래스의 메서드를 호출할수 있다.

super 호출할 때 주의 사항

  1. 서브 클래스에서 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();
  1. 서브 클래스의 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);
  1. super는 반드시 서브 클래스의 constructor 에서만 호출된다. 다른 함수에서 super호출하면 에러가 발생
class Base {
  constructor() {
    super(); //'super' keyword unexpected here
  }
}
function foo() {
  super(); //'super' keyword unexpected here
}

super 참조

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

class Base {
  constructor(name) {
    this.name = name;
  }

  sayHi() {
    return `hi ${this.name}`;
  }
}

class Derived extends Base {
  sayHi() {
    return `${super.sayHi()} how are you`;
  }
}

const derived = new Derived("suha");
console.log(derived.sayHi());

25.8.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 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' }

console.log(colorRectangle.getArea()); //8
console.log(colorRectangle.toString()); //width =2 height =4,color =red
  1. 서브 클래스의 super 호출 서브 클래스는 자신이 직접 인스턴스를 생성하지 않고 수퍼클래스에게 인스턴스 생성을 위임한다. 이것이 바로 constructor 에서 super 를 호출해야하는 이유이다 . 인스턴스를 생성하는 주체는 수퍼클래스이므로 수퍼 클래스의 construtor를 호출하는 super 가 호출되지 않으면 인스턴스를 생성할수 없다.
  2. 수퍼클래스의 인스턴스 생성과 this 바인딩 수퍼클래스의 constructor 내부의 코드가 실행되기 이전에 암묵적으로 빈객체 생성한다. 빈객체가 바로 클래스가 생성한 인스턴스 , 그리고 인스턴스는 this에 바인딩인스턴스는 수퍼 클래스가 생성할것이지만 new 연산자와 함께 호출된 클래스가 서브클래스라는것이 중요하다 . new 연산자와 함께 호출된 함수를 가리키는 new.target 은 서브클래스를 가르킨다 . 따라서 인스턴스는 new.target이 가리키는 서브클래스가 생성한 것으로 처리한다.
    1. 수퍼클래스의 인스턴스 초기화 수퍼클래스의 constructor가 실행되어 this에 바인딩되어 있는 인스턴스를 초기화 한다.
    class Rectangle {
      constructor(width, height) {
        console.log(this); //ColorRectangle {}
        //new 연산자와 함께 호출된 함수, 즉 new target은 ColorRectangle 이다
        console.log(new.target); //[class ColorRectangle extends Rectangle]
    
        //생성될 인스턴스의 프로토타입으로 ColorRectangle.prototype이 설정된다.
        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;
      }
    
    1. 서브클래스 contructor 로의 복귀와 this 바인딩 super 호출이 종료되고 제어흐름이 서브클래스 constructor 로 돌아온다. 이때 super가 반환한 인스턴스가 this에 바인딩 된다. 서브 클래스는 별도의 인스턴스를 생성하지 않고 super 가 반환한 인스턴스를 this에 바인딩하여 그대로 사용한다.
    super 가 호출되지 않으면 인스턴스가 생성되지 않으며 , this 바인딩도 할수 없다 . 서브클래스의 constructor 에서 super를 호출하기 전에는 this를 참조할수 없는 이유도 바로 이것 때문이다 . 2. 서브 클래스의 인스턴스 초기화 super 호출 이후 , 서브클래스의 constructor 에 기술되어 있는 인스턴스 초기화가 실행된다. this에 바인딩되어있는 인스턴스에 프로퍼티를 추가하고 constructor 가 인수로 전달받은 초기값으로 인스턴스의 프로퍼티를 초기화 한다. 3. 인스턴스 반환 클래스의 모든 처리가 끝나면 인스턴스가 바인딩된 this 가 암묵적으로 반환된다.
    class MyArray extends Array {
      //중복된 배열요소를 제거하고 반환
      uniq() {
        return this.filter((v, i, self) => self.indexOf(v) === i);
      }
      //모든 배열 요소의 평균을 구한다
      average() {
        return this.reduce((pre, cur) => pre + cur, 0) / this.length;
      }
    }
    
    const myArray = new MyArray(1, 1, 2, 3);
    console.log(myArray);
    console.log(myArray.uniq());
    console.log(myArray.average());
    
  3. 25.8.7 표준 빌트인 생성자 함수 확장
  4. class Rectangle { constructor(width, height) { console.log(this); //ColorRectangle {} console.log(new.target); //[class ColorRectangle extends Rectangle] this.width = width; this.height = height; } const colorRectangle = new ColorRectangle(2, 4, "red");

'개발 도서 > 자바스크립트 deepdive' 카테고리의 다른 글

23 실행 컨텍스트  (0) 2023.07.12
24 클로저  (0) 2023.07.12
16장 property attribute  (0) 2023.07.11
17 생성자 함수에 의한 객체 생성  (0) 2023.07.11
18 함수와 일급 객체  (0) 2023.07.11