์ด ๊ธ์ static ํค์๋์ ๊ธฐ๋ณธ ๊ฐ๋
๊ณผ ์ฉ๋, ๊ทธ๋ฆฌ๊ณ ์ค์ ์์๋ฅผ ํตํด
ํด๋์ค์ ์ ์ ๋ฉ์๋์ ์์ฑ์ ์ดํดํ๊ธฐ ์ฝ๊ฒ ์ค๋ช ํฉ๋๋ค.
ํด๋์ค์ ์ ์ ๋ฉ์๋์ ์์ฑ์ ์ดํดํ๊ธฐ ์ฝ๊ฒ ์ค๋ช ํฉ๋๋ค.
๐๋ชฉ์ฐจ
- ๊ธฐ๋ณธ ๋ฌธ๋ฒ
- static์ ์ฉ๋
- ๐ธ ์์ 1: ์ ํธ๋ฆฌํฐ ๋ฉ์๋
- ๐ธ ์์ 2: ํฉํ ๋ฆฌ ๋ฉ์๋ (๊ฐ์ฒด ์์ฑ ๋์ฐ๋ฏธ)
- ๐ธ ์์ 3: ์ ์ ์์ฑ (class-level ์์ ๋ฑ)
- static vs instance
- ์ฐธ๊ณ : 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 ๋ฑ์ ์ ํธ ๋ฉ์๋ |
'Developing๐ฉโ๐ป > Front-end' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Programming] ์ฑ๊ธํด ํจํด๊ณผ ๋์์ธํจํด (0) | 2025.07.13 |
---|---|
[JS] ํจ์ ์์๋ก ์ดํด๋ณด๋ static ๋ฉ์๋ ํ์ฉ๋ฒ (1) | 2025.07.13 |
[JS] JavaScript์์ ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ (OOP) 4๋ ํน์ฑ๊ณผ ์์ (0) | 2025.07.13 |
[typescript] ์กฐ๊ฑด๋ณ ํ์ ์ ํ๊ธฐ (0) | 2024.03.05 |
[React] state์ ๋ณ๊ฒฝ๊ณผ lodash์ debounce๋ฅผ ๋์์ ํธ์ถํ๊ธฐ (0) | 2024.03.04 |