์ด ๊ธ€์€ static ํ‚ค์›Œ๋“œ์˜ ๊ธฐ๋ณธ ๊ฐœ๋…๊ณผ ์šฉ๋„, ๊ทธ๋ฆฌ๊ณ  ์‹ค์ œ ์˜ˆ์‹œ๋ฅผ ํ†ตํ•ด
ํด๋ž˜์Šค์˜ ์ •์  ๋ฉ”์„œ๋“œ์™€ ์†์„ฑ์„ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ์„ค๋ช…ํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ”๋ชฉ์ฐจ

โœ… static์ด๋ž€?

static ํ‚ค์›Œ๋“œ๋Š” ํด๋ž˜์Šค์˜ ์ •์ (static) ๋ฉ”์„œ๋“œ๋‚˜ ์†์„ฑ์„ ์ •์˜ํ•  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
์ด๋Ÿฐ ๋ฉ”์„œ๋“œ/์†์„ฑ์€ ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค์—์„œ ํ˜ธ์ถœํ•  ์ˆ˜ ์—†๊ณ , ํด๋ž˜์Šค ์ž์ฒด์—์„œ๋งŒ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.


๊ธฐ๋ณธ ๋ฌธ๋ฒ•

class MyClass {
  static staticMethod() {
    console.log('๋‚˜๋Š” ํด๋ž˜์Šค์—์„œ ์ง์ ‘ ํ˜ธ์ถœ๋ฉ๋‹ˆ๋‹ค.');
  }

  instanceMethod() {
    console.log('๋‚˜๋Š” ์ธ์Šคํ„ด์Šค์—์„œ ํ˜ธ์ถœ๋ฉ๋‹ˆ๋‹ค.');
  }
}

MyClass.staticMethod();     // โœ… OK
const obj = new MyClass();
obj.instanceMethod();       // โœ… OK
obj.staticMethod();         // โŒ ์—๋Ÿฌ! ์ธ์Šคํ„ด์Šค์—์„œ๋Š” static ํ˜ธ์ถœ ๋ถˆ๊ฐ€

 

static์˜ ์šฉ๋„

 

์šฉ๋„ ์„ค๋ช… ์˜ˆ์‹œ

์œ ํ‹ธ๋ฆฌํ‹ฐ ๋ฉ”์„œ๋“œ ์ธ์Šคํ„ด์Šค์™€ ๋ฌด๊ด€ํ•œ ๋„์šฐ๋ฏธ ํ•จ์ˆ˜ Math.random(), Array.isArray()
๊ณต์šฉ ์„ค์ •/์ƒ์ˆ˜ ํด๋ž˜์Šค ์ˆ˜์ค€์—์„œ ๊ด€๋ฆฌํ•˜๋Š” ๊ฐ’ MyClass.defaultOptions
ํŒฉํ† ๋ฆฌ ๋ฉ”์„œ๋“œ ๊ฐ์ฒด ์ƒ์„ฑ์„ ๋„์™€์ฃผ๋Š” ํด๋ž˜์Šค ๋ฉ”์„œ๋“œ User.createFromJson()

๐Ÿ”ธ ์˜ˆ์‹œ 1: ์œ ํ‹ธ๋ฆฌํ‹ฐ ๋ฉ”์„œ๋“œ

class MathUtils {
  static add(a, b) {
    return a + b;
  }
}

console.log(MathUtils.add(3, 4)); // 7
  • ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ ์—†์ด ๋ฐ”๋กœ MathUtils.add() ํ˜ธ์ถœ ๊ฐ€๋Šฅ
  • Math.add()๋‚˜ Array.isArray()๋„ ์ด๋Ÿฐ static ๋ฐฉ์‹

๐Ÿ”ธ ์˜ˆ์‹œ 2: ํŒฉํ† ๋ฆฌ ๋ฉ”์„œ๋“œ (๊ฐ์ฒด ์ƒ์„ฑ ๋„์šฐ๋ฏธ)

class User {
  constructor(name) {
    this.name = name;
  }

  static fromJson(json) {
    const data = JSON.parse(json);
    return new User(data.name);
  }
}

const json = '{"name": "sally"}';
const user = User.fromJson(json);
console.log(user); // User { name: 'sally' }

๐Ÿ”ธ ์˜ˆ์‹œ 3: ์ •์  ์†์„ฑ (class-level ์ƒ์ˆ˜ ๋“ฑ)

class Config {
  static version = '1.0.0';

  static printVersion() {
    console.log(`๋ฒ„์ „: ${Config.version}`);
  }
}

Config.printVersion(); // ๋ฒ„์ „: 1.0.0

 

โ€ป ์ •์  ์†์„ฑ์€ ์ตœ์‹  JS(ES2022+) ๋ฌธ๋ฒ•์ด๋ฉฐ, Babel/webpack ์—†์ด ์“ฐ๋ ค๋ฉด ํ™˜๊ฒฝ ํ™•์ธ ํ•„์š”


static vs instance

ํ˜ธ์ถœ ๋Œ€์ƒ ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค
์ƒํƒœ ์ €์žฅ ์œ„์น˜ ํด๋ž˜์Šค์— ๊ท€์† ๊ฐ ์ธ์Šคํ„ด์Šค๋งˆ๋‹ค ๋ณ„๋„
์˜ˆ์‹œ Array.isArray(), Math.random() arr.push(), user.name

 


์ฐธ๊ณ : static์€ ์ƒ์†๋จ

class Parent {
  static hello() {
    console.log('hello');
  }
}
class Child extends Parent {}

Child.hello(); // โœ… hello (์ƒ์†๋จ)

 

ํŠน์ง• ์„ค๋ช…

์ •์˜ ์œ„์น˜ ํด๋ž˜์Šค ๋‚ด๋ถ€์—์„œ static ํ‚ค์›Œ๋“œ ์‚ฌ์šฉ
ํ˜ธ์ถœ ๋ฐฉ์‹ ํด๋ž˜์Šค๋ช….static๋ฉ”์„œ๋“œ()
๋ชฉ์  ์ธ์Šคํ„ด์Šค ์ƒํƒœ์™€ ๋ฌด๊ด€ํ•œ ํ•จ์ˆ˜๋‚˜ ์†์„ฑ ์ •์˜
์˜ˆ์‹œ Math, Array, Object, Date ๋“ฑ์˜ ์œ ํ‹ธ ๋ฉ”์„œ๋“œ

 

 

+ Recent posts