Static Method

// Animal.js
class Animal {
    constructor(name) {
        this.name = name;
    }
    
    getName() {
        return this.name;
    }
    
    static sleep() {
        console.log('Zzz');
    }
}

export default Animal;

메소드 앞에 static 키워드를 붙여주면 따로 인스턴스를 생성하지 않고 메소드를 호출할 수 있다.

// index.js
import Animal from './Animal';

let anim = new Animal('Jake');

Animal.sleep(); // 'Zzz'
anim.sleep(); // Uncaught TypeError: anim.sleep is not a function

인스턴스를 통해 static 메소드를 호출하면 TypeError가 발생한다.

Last updated