JavaScript

Static Methods, Prototype Methods 정리

whoyoung90 2022. 7. 17. 18:14
반응형

생성자함수 Array 입장에서 디렉터리 구조를 살펴보면

 

스태틱 메서드

from(), isArray(), of()

클래스(생성자함수)에서 직접 정의한 메서드

인스턴스에 상속(참조)되지 않는다.

인스턴스에서 직접 호출할 수 없고 클래스에서만 호출 가능.

 

프로토타입 메서드

map(), forEach(), pop() ...

클래스의 prototype 내부에 정의된 메서드

인스턴스에 상속(참조)가 가능하다.

인스턴스에서 직접 호출할 수 있다.

> 예시

/* 생성자 Constructor */
let Constructor = function(width, height) {
  this.width = width;
  this.height = height;
};

/* 프로토타입 메서드 */
Constructor.prototype.getMutiple = function() {
  return this.width * this.height;
};
/* 스태틱 메서드 (Object에 직접 부여) */
Constructor.getPlus = function(instance) {
  return instance instanceof Constructor &&
  instance.width + instance.height;
};

const inst = new Constructor(3, 4);

console.log(inst.getMutiple());         // 12 프로토타입 메서드
console.log(inst.getPlus(inst));        // TypeError
console.log(Constructor.getPlus(inst)); // 7 스태틱 메서드

 

반응형