개념

Class

Pasted image 20240406075045.png

상하 관계가 존재하는 카테고리 superclass > subclass

Pasted image 20240406074943.png

Instance

위의 사진처럼 각 특성 (먹을 수 있음, 나무에서 열림 등등) 들을 가지고 있는 실존하는 개체를 Instance 라고 한다.

Instance를 생성할 때 호출할 수 있는 클래스는 오직 하나 뿐이다.

컴퓨터에서는 클래스가 먼저 정의되어야만 그로부터 공통적인 요소를 지니는 개체들을 생성할 수 있다.

JS의 Class

JS는 prototype기반이기 때문에 Class를 흉내내는 것 뿐이지만 비슷하게 볼 점들이 많다.

예시로 보는 공통점

  1. 생성자 함수 Array를 new와 함께 호출해서 instance 생성
  2. instance에 Array의 prototype 객체 내부 요소들이 "상속" (사실 참조가 맞는 말인데 동일하게 작동함.)
  3. prototype을 제외한 Array 내부 property들은 "상속"되지 않음 (static member와 instance member)

차이점

JS에서는 인스턴스에서도 직접 method를 정의할 수 있다

instance에서 prototype에서 직접 호출할 수 있는 method (prototype method)

20240406_082524.jpg

// constructor
var Rectangle = function (width, height) {
  this.width = width;
  this.height = height;
};

// prototype method
// 인스턴스에서 직접 호출할 수 있는 method (__proto__는 생략할 수 있기 때문)
Rectangle.prototype.getArea = function () {
  return this.width * this.height;
};

// static method
// prototype 안에 들어간게 아니라서 참조가 되지 않음. (상속x)
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)); //TypeError: not a function
console.log(Rectangle.isRectangle(rect1)); //true