Static
- ๊ฐ์ฒด์ ๊ท์๋์ง ์๋๋ค.
- ํด๋์ค์ ์ง์ ๊ท์๋ผ์ new๋ก ์ธ ํ์ ์๋ค.
class Person {
name;
year;
static groupName = '์ค';
constructor(name, year) {
this.name = name;
this.year = year;
}
// ํจ์๋ ๊ฐ๋ฅ
static returnGroupName() {
return '์ค';
}
}
const soo = new Person('soo', 1997);
// ๊ฐ์ฒด์ ๊ท์๋์ง ์๋๋ค.
console.log(soo); // Person { name: 'soo', year: 1997 }
// ๊ทธ๋ผ ์ด๋์ ๊ท์๋ผ์๋?
// ํด๋์ค ์์ฒด์ ๊ท์๋์ด์๋ค!
console.log(Person.groupName) // ์ค
console.log(Person.returnGroupName()) // ์ค
Static ์ฌ์ฉํด์ Factory Constructor ์์ฑ ํจํด ์ ์ฉํด๋ณด๊ธฐ
- ์ธ์คํด์ค๋ฅผ ๋ฐํ๋ฐ์ง ์๊ณ ๋ฏธ๋ฆฌ ์ด๋ค ๋ฐ์ดํฐ๋ฅผ ์ ๋ ฅ๋ฐ์์ ํด๋น ์ธ์คํด์ค๋ฅผ ๋ง๋ค์ง ํ ํ๋ฆฟํํด์ ์ธ ์ ์๋ ์ฅ์ ์ด ์๋ค.
class Person {
name;
year;
constructor(name, year) {
this.name = name;
this.year = year;
}
static fromObject(object) {
return new Person(object.name, object.year);
}
static fromList(list) {
return new Person(list[0], list[1]);
}
}
// new๋ฅผ ์ฐ์ง ์์๋ ๊ฐ์ฒด๋ฅผ ๋ฐํํด์ฃผ๊ธฐ ๋๋ฌธ์ ํธ๋ฆฌํ ํจํด์ค ํ๋
const soo = Person.fromObject({
name: "soo",
year: 1997,
});
console.log(soo); // Person { name: 'soo', year: 1997 }
const soo2 = Person.fromList(["soo2", 1997]);
console.log(soo2); // Person { name: 'soo2', year: 1997 }
Static
- ๊ฐ์ฒด์ ๊ท์๋์ง ์๋๋ค.
- ํด๋์ค์ ์ง์ ๊ท์๋ผ์ new๋ก ์ธ ํ์ ์๋ค.
class Person {
name;
year;
static groupName = '์ค';
constructor(name, year) {
this.name = name;
this.year = year;
}
// ํจ์๋ ๊ฐ๋ฅ
static returnGroupName() {
return '์ค';
}
}
const soo = new Person('soo', 1997);
// ๊ฐ์ฒด์ ๊ท์๋์ง ์๋๋ค.
console.log(soo); // Person { name: 'soo', year: 1997 }
// ๊ทธ๋ผ ์ด๋์ ๊ท์๋ผ์๋?
// ํด๋์ค ์์ฒด์ ๊ท์๋์ด์๋ค!
console.log(Person.groupName) // ์ค
console.log(Person.returnGroupName()) // ์ค
Static ์ฌ์ฉํด์ Factory Constructor ์์ฑ ํจํด ์ ์ฉํด๋ณด๊ธฐ
- ์ธ์คํด์ค๋ฅผ ๋ฐํ๋ฐ์ง ์๊ณ ๋ฏธ๋ฆฌ ์ด๋ค ๋ฐ์ดํฐ๋ฅผ ์ ๋ ฅ๋ฐ์์ ํด๋น ์ธ์คํด์ค๋ฅผ ๋ง๋ค์ง ํ ํ๋ฆฟํํด์ ์ธ ์ ์๋ ์ฅ์ ์ด ์๋ค.
class Person {
name;
year;
constructor(name, year) {
this.name = name;
this.year = year;
}
static fromObject(object) {
return new Person(object.name, object.year);
}
static fromList(list) {
return new Person(list[0], list[1]);
}
}
// new๋ฅผ ์ฐ์ง ์์๋ ๊ฐ์ฒด๋ฅผ ๋ฐํํด์ฃผ๊ธฐ ๋๋ฌธ์ ํธ๋ฆฌํ ํจํด์ค ํ๋
const soo = Person.fromObject({
name: "soo",
year: 1997,
});
console.log(soo); // Person { name: 'soo', year: 1997 }
const soo2 = Person.fromList(["soo2", 1997]);
console.log(soo2); // Person { name: 'soo2', year: 1997 }