타입스크립트로 여러가지 기능이있는 백과사전을 만들어보는 과제를 진행했었다.
JS를 처음 공부할때 this 키워드가 눈에 잘 띄고 계속 궁금해서 가끔식 읽어보고 까먹고 찾아보고
한적이 있었는데 이기회에 제대로 머릿속에 넣은 기분이다.
type Words = {
[key: string]: string;
};
객체에서 어떤 메서드인지 명확하진 않지만 타입만 알수있을때는 유용하다.
class Word {
constructor(public term: string, public def: string) {
{ }
}
}
class Dict {
public words: Words;
constructor() {
this.words = {};
}
단어를 담을 constructor 함수를 선언한다.
add(word: Word) {
if (!this.words[word.term]) {
this.words[word.term] = word.def;
}
else console.log("이미 정의된 단어");
}
get(word: Word) {
if (this.words[word.term]) {
return console.log(word.def);
}
}
호출할때 인자를 아래 단어를 먼저 cosnt에 담는 과정에서
const만 엄청 불러놓고 왜 update함수 실행후 반영이 안되냐고 30분동안 머리싸매고있었다.
delete(word: Word) {
if (this.words[word.term]) {
delete this.words[word.term];
console.log(`${word.term}이 삭제됨`);
} else console.log("정의되지 않은 단어.");
}
update(word: Word, newDef: string) {
if (this.words[word.term]) {
this.words[word.term] = newDef;
console.log("업데이트 성공");
} else console.log("정의되지 않은 단어.");
}
오늘 함수 구현중에 제일 고민했지만 깔끔하게 짜여진거같아서 맘에들었다.
count() {
return console.log(`총 단어의갯수 : ${Object.keys(this.words).length}`)
}
생각지도 못한곳에서 객체의 맛을 봤다.
.length만 그냥 붙혀서 실행해봤더니 undefine이 리턴 되어서 검색해보니
Object.key(객체)를 실행하면 객체의 key를 담은 배열이 리턴된다.
그 key의 갯수 = 객체의 갯수 이기때문에 .length 를 붙혀 객체의 크기를 구할 수있었다.
const yasuo = {
a:"1" , b : "2" , c : "3", d : "4" e : "5"
}
가 있을때. Object.key(yasuo) 를 실행하면
[a, b, c, d, e] 가 리턴된다.
showAll() {
return console.log(this.words);
}
const soiSoruceCrap = new Word("간장게장", "밥도둑 간장게장등딱지슉슈슈슉");
const jjamBBong = new Word("짬뽕", "술마시고다음날죽인다카이");
const tong_sae_woobuger = new Word("통새우버거", "버거킹에서 이것만 시켜먹는다");
const mintCokoIce = new Word("민트초코아이스크림", "사양한다.");
const dict = new Dict();
dict.add(soiSoruceCrap);
dict.add(jjamBBong);
dict.add(tong_sae_woobuger);
dict.add(mintCokoIce);
dict.showAll()
dict.count()
dict.delete(mintCokoIce);
dict.showAll()
dict.count()
dict.update(jjamBBong, "맛있다.");
dict.showAll()
dict.get(tong_sae_woobuger);
dict.count()
타입스크립트에서 class를 맛봤다. 평소에 궁금했던 this 키워드를 확실하게 공부할수있어서
좋은 경험이었던 같다. react, Next, node.js를 맛보던 어느 프레임워크, 라이브러리를 공부하더라도
바닐라 js의 기초가 부족하다고 절실히 느끼고있다. 특히 class와 객체지향을 컨셉으로 잡고 프로젝트를
진행해본적이 없어서 더욱더 부족한거같다. 앞으로 객체지향을 사용하는 언어나, 컨셉을 공부하는쪽으로 방향을
잡아야 할꺼같다.