본문 바로가기

JavaScript

[Core JavaScript] class

JavaScript는 프로토타입 기반 언어이므로 클래스 개념이 존재하지 않습니다.

생성자 함수 Array를 new 연산자와 함께 호출하면 인스턴스가 생성됩니다. 이때 Array를 일종의 클래스라고 하면, Array의 prototype 객체 내부 요소들이 인스턴스에 상속된다고 볼 수 있습니다. 엄밀히는 상속이 아닌 프로토 타입 체이닝에 의한 참조이지만 결과적으로는 동일하게 동작하므로 이렇게 이해해도 무방합니다. 한편 Array 내부 프로퍼티들 중 prototype 프로퍼티를 제외한 나머지는 인스턴스에 상속되지 않습니다.

인스턴스에 상속되는지( 인스턴스가 참조하는지 ) 여부에 따라 스태틱 멤버와 인스턴스 멤버로 나뉩니다. 이 분류는 다른 언어의 클래스 구성요소에 대한 정의를 차용한 것으로서 클래스 입장에서 사용 대상에 따라 구분한 것입니다.

const Rectangle = function (width, height ) {
    this.width = width;
      this.height = height;
}
Rectangle.prototype.getArea = function () {
    return this.width * this.height;
} // 프로토타입 메서드 (인스턴스 메서드)
Rectangle.isRectangle =function (instance) {
    reuturn instance instanceof Rectangle && 
      instance.width > 0 && instance.height > 0;
} // 스태틱 메서드
const rect1 = new Rectangle(3,4); 
console.log(rect1.getArea()) // 12
console.log(rect1.isRectangle(rect1))  error (x)
console.log(Rectangle.isRectangle(rect1)); true

프로토타입 객체에 할당한 메서드는 인스턴스가 마치 자신의 것처럼 호출할 수 있습니다. 위에서 getArea는 실제로는 rect1.__proto__.getArea 에 접근하는데, 이때 __proto__를 생략했으므로 this가 rect1 인채로 실행되니까, 결과적으로는 rect1.width * rect1.height 를 계산합니다. 이처럼 인스턴스에서 직접 호출할 수 있는 메서드가 프로토타입 메서드입니다.  스태틱 메서드는 인스턴스에서 접근할 수 없습니다.  클래스 자체를 this로 해서 직접 접근해야 하는 스태틱 메서드를 호출할 때는 클래스는 그 자체가 하나의 개체로서 취급됩니다. 

'JavaScript' 카테고리의 다른 글

[Core JavaScript] VariableEnvironment & LexicalEnvironment  (0) 2022.03.06
[JavaScript] fetch  (0) 2022.03.04
[Modern JavaScript Deep Dive] Array  (0) 2022.03.03
[Modern JavaScript Deep Dive] Iterable  (0) 2022.03.02
[JavaScript] CustomEvent  (0) 2022.03.01