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