class Player {
constructor(
private firstName : string, //class 내부에서만 사용 가능
private lastName : string,
public nickname : string //class 외부 호출 가능 -> ex) console.log(Player.nickname)
) {}
}
const FUNco = new Player("FUN", "co", "펀코");
abstract class User {
constructor(
private firstName : string,
private lastName : string,
public nickname : string
) {}
} // 다른 클래스가 상속받을 수 있음 (상속만 가능)
class Player extends User {
}
const FUNco = new User("FUN", "co", "펀코"); // error 추상클래스로는 인스턴스 생성 불가
const FUNco = new Player("FUN", "co", "펀코"); // no error
abstract class User {
constructor(
private firstName : string,
private lastName : string,
public nickname : string
) {}
getFullName(){
return `${this.firstName} ${this.lastName}`
}
}
class Player extends User {
}
// Player는 User를 상속받았기 때문에 Player.getFullName() 가능
위와같이 firstName
과lastName
을 private로 설정했더니 상속받은 Player
에서 호출할 수 없다.
외부로부터 보호받지만 위 경우처럼 상속받은 클래스에서 사용할수 있도록 하려면 protected
를 사용한다.
type Words = {
[key: string] : string
};
class Dict {
private words: Words
constructor() {
this.words = {}
}
add(word: Word) {
if(this.words[word.term] === undefined) {
this.words[word.term] = word.def;
} // class를 type으로 사용
}
def(term: string){
return this.words[term]
}
};
class Word {
constructor(
public term : string,
public def: string
) {}
};
const kimchi = new Word("kimchi","한국의 음식");
const dict = new Dict();
dict.add(kimchi); // {term : "kimchi", def : "한국의 음식"} 객체 입력
dict.def("kimchi"); // '한국의 음식'