본문 바로가기
  • soldonii's devlog
Javascript 공부/TIL

200206(목) : Static Method vs. Instance Method

by soldonii 2020. 2. 6.

자바스크립트에서 Static Method와 Instance Method는 어떤 차이가 있는지 정리하는 글이다.

 

1. Static Method

  • 정적 메소드는 클래스의 인스턴스 없이도 호출이 가능하지만, 클래스가 인스턴스화되면 호출이 불가능하다.
  • 다른 static method 내부에서 기존의 static method에 접근하고자 할 때에는 this keyword를 사용할 수 있다.
  • class 키워드를 이용해서 구현할 때에는 static 키워드로 선언할 수 있다.
  • 생성자 호출을 할 함수를 이용해서 구현할 때에는 직접 함수에 메소드를 추가하는 방식으로 선언할 수 있다.

 

// 1. class 키워드와 static 키워드를 이용해서 정적 메소드를 선언하는 경우.
class StaticMethodCall {
  static staticMethod() {
    return 'Static method has been called';
  }
  static anotherStaticMethod() {
    return this.staticMethod() + ' from another static method';
  }
}

StaticMethodCall.staticMethod(); // 'Static method has been called'
StaticMethodCall.anotherStaticMethod(); // 'Static method has been called from another static method'

// 인스턴스화되면 정적 메소드는 사용이 불가능하다.
const instance = new StaticMethodCall();
instance.staticMethod(); // Uncaught TypeError: instance.staticMethod() is not a function
// 2. 생성자 호출을 할 함수를 이용해서 구현하는 경우.
function StaticMethodCall () {};

StaticMethodCall.staticMethod = function () {
  return 'Static method has been called';
}

StaticMethodCall.anotherStaticMethod = function () { // this 키워드로 다른 static method에 접근.
  return this.staticMethod() + ' from another static method';
}

StaticMethodCall.staticMethod(); // 'Static method has been called'
StaticMethodCall.anotherStaticMethod(); // 'Static method has been called from another static method'

// 인스턴스화되면 정적 메소드는 사용이 불가능하다.
const instance = new StaticMethodCall();
instance.staticMethod(); // Uncaught TypeError: instance.staticMethod() is not a function

 

  • 하나의 클래스 내부에서 static 메소드의 수는 제한이 없다.
  • 비정적 메소드에서 정적 메소드를 호출하는 것은 this로는 불가능하다. class 이름 혹은 this.constructor를 이용해야 접근이 가능하다.

 

class StaticMethodCall {
  constructor() {
    console.log(StaticMethodCall.staticMethod());
    // 'static method has been called.'

    console.log(this.constructor.staticMethod());
    // 'static method has been called.'
  }

  static staticMethod() {
    return 'static method has been called.';
  }
}

 

2. Instance Method

  • 인스턴스 메소드는 클래스가 인스턴스 객체로 생성되었을 때 해당 인스턴스가 사용할 수 있는 메소드이다.
  • 구현 방식에 따라 다르지만, 클래스가 객체로 인스턴스화 되었을 때 해당 인스턴스에 내장되어 있거나 혹은 프로토타입 상위로부터 상속 받아 사용하게 된다.
// 1. constructor 내부에 직접 프로퍼티와 메소드를 입력하여 모든 인스턴스가 아래 3개의 프로퍼티와 run, changeColor 메소드를 가지게 된다.
class Car {
  constructor (name, color, maxSpeed) {
    this.name = name;
    this.color = color;
    this.maxSpeed = maxSpeed;

    this.run = function () {
      return `The car ${this.name} is running with speed of ${this.maxSpeed}km/h.`;
    }

    this.changeColor = function () {
      return `I'd like to change the color of the car from ${this.color} to red.`
    }
  }
}
// 2. 이제 run과 changeColor 함수는 인스턴스에는 존재하지 않는다. 인스턴스의 상위 prototype 객체에 존재하며 이를 상속받아 사용한다.
class Car {
  constructor (name, color, maxSpeed) {
    this.name = name;
    this.color = color;
    this.maxSpeed = maxSpeed;
  }

  run () {
    return `The car ${this.name} is running with speed of ${this.maxSpeed}km/h.`;
  }

  changeColor = function () {
    return `I'd like to change the color of the car from ${this.color} to red.`
  }
}

 

3. 언제 무엇을 사용할까?

static class에 대해서 조사해보면 거의 대부분 프로그램의 utility 함수를 만들 때 사용한다고 쓰여만 있고, 실 예제 같은게 거의 없어서 완벽히 이해는 못 했다. 다만 자바스크립트에서 대표적인 static 메소드를 살펴보자면...

  • Array.isArray(), Object.assign() 같은 메소드가 바로 대표적인 static method이다.
  • Array 클래스와 Object 클래스가 직접적으로 가지고 있지만, 인스턴스들은 해당 메소드를 가지고 있지 않다.

 

Array.isArray()의 경우 인자로 받는 대상이 배열인지 아닌지 판별하는 메소드이다. 판별하고자 하는 대상이 배열인지, 문자열인지, 어떤 데이터 타입인지 모르는 상태이기 때문에 인스턴스 메소드로는 이를 사용할 수가 없는 것이다. 따라서 이를 Array class 내부의 정적 메소드로 만든 것이다.

 

Object.assign()도 마찬가지이다. 하나의 인스턴스를 가지고 작업하는 것이 아니라, 여러 개의 객체 인스턴스를 인자로 받아서 새로운 객체를 리턴시키는 메소드이기 때문에 어떤 인스턴스의 메소드가 아니라 Object class의 정적 메소드로 사용하는 것이 용도에 맞는 방식이다.

댓글