코어자바스크립트 7장<클래스>

김정현·2021년 2월 21일
1
post-thumbnail

클래스

자바스크립트는 프로토타입 기반 언어라서 '상속' 개념이 존재하지 않는다.
ES6에 클래스 문법이 추가되었다.
ES6의 클래스에서도 일정 부분은 프로토타입을 활용하고 있기 때문에, ES5에서 클래스를 흉내내기 위한 구현 방식을 학습하는 것은 큰 의미가 있다.

1. 클래스와 인스턴스의 개념 이해

▶ 음식(superClass) - 과일(subClass/superClass) - 귤류(subClass) - 오렌지(element) ◀

  • 음식 > 과일 > 귤 류 > 오렌지" 관계 일 때, 음식은 과일 보다 상위(superior)의 개념, 과일은 음식보다 하위(subordinate)의 개념
  • 음식은 과일의 superclass, 과일은 귤 류의 subclass, 음식은 귤 류의 super-superclass 귤 류는 음식의 sub-subclass
  • 오렌지는 클래스의 구체적인 예시, 즉 인스턴스(instance)

2. 자바스크립트의 클래스

자바스크립트는 프로토타입 기반 언어임 따라서 클래스의 개념이 존재하지 않지만, 프로토타입은 일반적인 관점에서 클래스와 비슷하게 해석할 수 있다.

생성자 함수 Array를 new 연산자와 함께 호출하면(const arrayInstance = new Array()) 인스턴스가 생성된다.
이때 Array를 일종의 클래스라고 생각하면, Array의 prototype 객체 내부 요소들이 인스턴스(Instance)에
'상속'된다고 볼 수 있음.

인스턴스에 상속되는지(인스턴스가 참조하는지) 여부에 따라 스태틱 멤버인스턴스 멤버로 나뉜다.
→ 자바스크립트 커뮤니티에서는 인스턴스 메서드 대신 프로토타입 메서드라고 더 많이 사용함.

// 예제 7-1 스태틱 메서드, 프로토타입 메서드
var Rectangle = function(width, height) {
    // 생성자
    this.width = width;
    this.height = height;
}
Rectangle.prototype.getArea = function() {
    // (프로토타입) 메서드
    return this.width * this.height;
}
Rectangle.isRectangle = function(instance) {
    // 스태틱 메서드
    return instance instanceof Rectangle && instance.width > 0 && instance.height > 0
}
var rect1 = new Rectangle(3,4)
console.log(rect1.getArea());
/**
 * 답: 12
 * 해설: [프로타입 메서드] rect1.__proto__.getArea
*/ 
console.log(rect1.isRectangle(rect1)); 
/**
 * 답: Error
 * 해설: rect1 인스턴스에 메서드 없음, rec1.__proto__ 에 없음, rect1.__proto__.__proto__ (=Object.prototype) 없음
*/
console.log(rect1.Rectangle.isRectangle(rect1)); 
/**
 *  답: true
 *  해설: [static 메서드]생성자 함수를 this로 해야만 호출가능
 */


3. 클래스 상속

클래스 상속을 흉내내기 위한 세가지 방법

  • subClass.prototypesuperClass의 인스턴스를 할당한 다음 프로퍼티를 모두 삭제하는 방법
  • 빈 함수(Bridge)를 활용하는 방법
  • Object.create를 이용하는 방법

4. ES6의 클래스 및 클래스 상속


ES5와 ES6의 클래스 문법 비교

// ES5

var ES5 = function (name) {
  this.name = name;
};
ES5.staticMethod = function () {
  return this.name + ' staticMethod';
};
ES5.prototype.method = function () {
  return this.name + ' method';
};
var es5Instance = new ES5('es5');
console.log(ES5.staticMethod()); // es5 staticMethod
console.log(es5Instance.method()); // es5 method
// ES6

var ES6 = class {
  constructor (name) {
    this.name = name;
  }
  static staticMethod () {
    return this.name + ' staticMethod';
  }
  method () {
    return this.name + ' method';
  }
};
var es6Instance = new ES6('es6');
console.log(ES6.staticMethod()); // es6 staticMethod
console.log(es6Instance.method()) // es6 method
  • class 라는 명령어 뒤에 바로 { } 가 등장하는데, 이 중괄호 묶음의 내부가 클래스 본문 영역이다.
  • constructor라는 이름 뒤에 바로 ( ) { 가 등장한다. 클래스 본문에서는 function 키워드를 생략하더라도 모두 메서드로 인식한다. 이름처럼 ES5의 생성자 함수와 동일하다.
  • 메서드와 다음 메서드 사이는 콤마로 구분하지 않는다.
  • static 키워드로 시작하는 메서드는 ES5에서 생성자 함수에 바로 할당하는 메서드와 동일하게 생성자 함수(클래스)만이 호출할 수 있다.
  • method가 바로 나오는 부분은 자동으로 prototype 객체 내부에 할당되는 메서드이다. ES5.prototype.method와 동일하게 인스턴스가 프로토타입 체이닝을 통해 마치 자신의 것처럼 호출할 수 있는 메서드이다.

0개의 댓글