์ ๊ทผ ์ ํ์
์ ๊ทผ ์ ํ์ ?
TS ์์๋ ์ ๊ทผ ์ ํ์(access modifiers)๋ฅผ ์ฌ์ฉํ์ฌ ํด๋์ค์ ๋ฉค๋ฒ(์์ฑ๊ณผ ๋ฉ์๋)์ ๋ํ ์ ๊ทผ ๊ถํ์ ์ ์ดํ ์ ์๋ค.
์ ๊ทผ ์ ํ์๋ ํด๋์ค ๋ด๋ถ์ ์ธ๋ถ์์ ํด๋น ์์ฑ์ ์ ๊ทผํ๋ ๋ฒ์๋ฅผ ๊ฒฐ์ ํฉ๋๋ค.
TS ์ ์ฃผ์ ์ ๊ทผ ์ ํ์
1. public
2. protected
3. private
public
public ์ ๊ฐ์ฅ ๊ธฐ๋ณธ ๊ฐ์ด๋ค.
๋ฉค๋ฒ์ public ์ ๊ทผ ์ ํ์๊ฐ ์ค์ ๋์ด ์๋ค๋ฉด, ํด๋น ๋ฉค๋ฒ๋ ํด๋์ค ์ธ๋ถ์์๋ ์ ๊ทผ์ด ๊ฐ๋ฅํ๋ค.
class Person {
public name: string;
constructor(name: string) { this.name = name; }
}
const person = new Person("Alice");
console.log(person.name); // ์ ๊ทผ
public ํน์ง
ํด๋์ค๋ด๋ถ ์ ๊ทผ ๊ฐ๋ฅ ์ฌ๋ถ : O
์์ ํด๋์ค๋ด๋ถ ์ ๊ทผ ๊ฐ๋ฅ ์ฌ๋ถ : O
ํด๋์ค ์ธ์คํด์ค ์ ๊ทผ ๊ฐ๋ฅ ์ฌ๋ถ : O
protected:
protected ์ ๊ทผ ์ ํ์๊ฐ ์ค์ ๋ ๋ฉค๋ฒ๋
ํด๋น ํด๋์ค ๋ด๋ถ ๋ฐ ํด๋น ํด๋์ค๋ฅผ ์์๋ฐ์ ํ์ ํด๋์ค์์๋ง ์ ๊ทผํ ์ ์๋ค.
class Animal {
protected sound: string;
constructor(sound: string) {
this.sound = sound;
}
makeSound() { console.log(this.sound); // ํด๋์ค ๋ฐ ํ์ ํด๋์ค ๋ด๋ถ์์ ์ ๊ทผ ๊ฐ๋ฅ }
}
class Dog extends Animal {
constructor() {
super("Bark");
}
bark() {
this.makeSound(); // ํ์ ํด๋์ค์์ ์์๋ protected ๋ฉค๋ฒ์ ์ ๊ทผ ๊ฐ๋ฅ
}
}
const dog = new Dog();
console.log(dog.sound); // ์ค๋ฅ: protected ๋ฉค๋ฒ๋ ํด๋์ค ์ธ๋ถ์์ ์ ๊ทผ ๋ถ๊ฐ๋ฅ
dog.bark(); // ํ์ ํด๋์ค ๋ด๋ถ ๋ฉ์๋๋ฅผ ํตํด ์ ๊ทผ ๊ฐ๋ฅ
์ด๋ฌํ ์ ๊ทผ ์ ํ์๋ฅผ ํตํด ํด๋์ค์ ๋ฉค๋ฒ์ ๋ํ ์ ์ ํ ์ ๊ทผ ๋ฒ์๋ฅผ ์ค์ ํ์ฌ ์ ๋ณด ์๋(Encapsulation)์ ์ ์งํ๊ณ , ์ฝ๋์ ์์ ์ฑ๊ณผ ์ ์ง๋ณด์์ฑ์ ๋์ผ ์ ์์ต๋๋ค.
protected ํน์ง
ํด๋์ค๋ด๋ถ ์ ๊ทผ ๊ฐ๋ฅ ์ฌ๋ถ : O
์์ ํด๋์ค๋ด๋ถ ์ ๊ทผ ๊ฐ๋ฅ ์ฌ๋ถ : O
ํด๋์ค ์ธ์คํด์ค ์ ๊ทผ ๊ฐ๋ฅ ์ฌ๋ถ : X
private
private ์ ๊ทผ ์ ํ์๊ฐ ์ค์ ๋ ๋ฉค๋ฒ๋ ํด๋น ํด๋์ค ๋ด๋ถ์์๋ง ์ ๊ทผํ ์ ์๋ค.
์ธ๋ถ์์๋ ์ ๊ทผ์ด ๋ถ๊ฐ๋ฅ ํ๋ค.
class Person {
private age: number;
constructor(age: number) { this.age = age; }
getAge() { return this.age; // ํด๋์ค ๋ด๋ถ์์ ์ ๊ทผ ๊ฐ๋ฅ }
}
const person = new Person(30);
console.log(person.age); // ์ค๋ฅ: ์ ๊ทผ ๋ถ๊ฐ๋ฅ
console.log(person.getAge()); // ๋ด๋ถ ๋ฉ์๋๋ฅผ ํตํด ์ ๊ทผ ๊ฐ๋ฅ
private ํน์ง
ํด๋์ค๋ด๋ถ ์ ๊ทผ ๊ฐ๋ฅ ์ฌ๋ถ : O
์์ ํด๋์ค๋ด๋ถ ์ ๊ทผ ๊ฐ๋ฅ ์ฌ๋ถ : X
ํด๋์ค ์ธ์คํด์ค ์ ๊ทผ ๊ฐ๋ฅ ์ฌ๋ถ : X
#ts #utilitytype #public #protected #private
'TS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[TS] : utility type (0) | 2023.08.22 |
---|---|
[TS] : any unknown union (0) | 2023.08.21 |
[TS] : tuple enum (0) | 2023.08.18 |
[TS] : .d.ts (0) | 2023.08.17 |
[TS] : tsconfig.json (0) | 2023.08.17 |