코어 자바스크립트 (7. 클래스)

문린이·2023년 2월 2일
0

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

프로그래밍 언어에서의 클래스는 현실세계에서의 클래스와 마찬가지로 '공통 요소를 지니는 집단을 분류하기 위한 개념'이라는 측면에서는 일치하지만 인스턴스들로부터 공통점을 발견해서 클래스를 정의하는 현실과 달리, 클래스가 먼저 정의돼야만 그로부터 공통적인 요소를 지니는 개체들을 생성할 수 있다.

7-2 자바스크립트의 클래스

// 생성자
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
console.log(rect1.isRectangle(rect1)); // Error
console.log(Rectangle.isRectangle(rect1)); // true

(1) 프로토타입 메서드 : 인스턴스에서 직접 호출할 수 있는 메서드
(2), (3) 스태틱 메서드 : 인스턴스에서 직접 접근할 수 없는 메서드 (생성자 함수를 this로 해야만 호출할 수 있다.)

7-3 클래스 상속

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

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

이 3 방법 모두 constructor 프로퍼티가 원래의 생성자 함수를 바라보도록 조정해야 한다.

7-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 문법

  1. constructor는 ES5의 생성자 함수와 동일한 역할을 수행 (클래스 본문에서는 function 키워드를 생략하더라도 모두 메서드로 인식
  2. 메서드와 다음 메서드 사이에는 콤마로 쿠분하지 않는다.
  3. static 키워드는 해당 메서드가 static 메서드임을 알리는 내용으로, ES5 체계에서 생성자 함수에 바로 할당하는 메서드와 동일하게 생성자 함수(클래스) 자신만이 호출할 수 있다.
  4. method는 ES5.prototype.method와 동일하게, 인스턴스가 프로토타입 체이닝을 통해 마치 자신의 것처럼 호출할 수 있는 메서드이다.

ES6의 클래스 상속

var Rectangle = class {
	constructor (width, height){
    	this.width = width;
      	this.height = height;
    }
  	getArea(){
    	return this.width * this.height;
    }
};
var Square = class extends Rectangle {
	constructor (width)	{
    	super(width, width);
    }
  	getArea(){
    	console.log('size is :', super.getArea());
    }
};
  1. Square를 Rectangle 클래스를 상속받는 SubClass로 만들기 위해 class 명령어 뒤에 extends Rectangle 이라는 내용을 추가 -> 이것으로 상속 관계 설정
  2. constructor 내부에서는 super라는 키워드를 함수처럼 사용할 수 있는데, 이 함수는 SuperClass의 constructor를 실행한다.
  3. constructor 메서드를 제외한 다른 메서드에서는 super 키워드를 마치 객체처럼 사용할 수 있고, 이때 객체는 SuperClass.prototype을 바라보는데, 호출한 메서드의 this는 super가 아닌 원래의 this를 그대로 따른다.

7-5 정리

  • 클래스는 어떤 사물의 공통 속성을 모아 정의한 추상적인 개념이고, 인스턴스는 클래스의 속성을 지니는 구체적인 사례 (상위 클래스(superClass)의 조건을 충족하면서 더욱 구체적인 조건이 추가된 것을 하위 클래스(subClass)라고 한다.)

  • 클래스의 prototype 내부에 정의된 메서드를 프로토타입 메서드라고 하며, 이들은 인스턴스가 마치 자신의 것처럼 호출할 수 있다.

  • 클래스에 직접 정의한 메서드를 스태틱 메서드라고 하며, 이들은 인스턴스가 직접 호출할 수 없고 클래스(생성자 함수)에 의해서만 호출할 수 있다.

profile
Software Developer

0개의 댓글