ํ๋ก ํธ์๋/TypeScript
ํด๋์ค
by alswlfl
2023. 1. 3.
ํด๋์ค
- ํ์
์คํฌ๋ฆฝํธ์์๋ ๋ฉค๋ฒ ๋ณ์๋ ๋ฏธ๋ฆฌ ์ ์ธํด์ฃผ์ด์ผ ํจ
class Car{
color:string; //ํ์
์คํฌ๋ฆฝํธ์์๋ ๋ฉค๋ฒ๋ณ์๋ ๋ฏธ๋ฆฌ ์ ์ธํด์ฃผ์ด์ผ ํจ
constructor(color:string){
this.color=color;
}
start(){
console.log("start");
}
}
const bnw=new Car("red");
- ๋ฉค๋ฒ ๋ณ์ ๋ฏธ๋ฆฌ ์ ์ธํ์ง ์๋ ๋ฐฉ๋ฒ -> ์ ๊ทผ ์ ํ์ ๋๋ readonlyํค์๋ ์ด์ฉ
class Car2{
constructor(public color:string){
this.color=color;
}
start(){
console.log("start");
}
}
class Car3{
constructor(readonly color:string){
this.color=color;
}
start(){
console.log("start");
}
}
์ ๊ทผ ์ ํ์(Access modifier) - public, private, protected
- ํ์
์คํฌ๋ฆฝํธ์์๋ ์ ๊ทผ ์ ํ์ ์ง์
- public: ์์ํด๋์ค๋ ํด๋์ค ์ธ์คํด์ค์์ ๋ชจ๋ ์ ๊ทผ ๊ฐ๋ฅ(์๋ฌด๊ฒ๋ ํ์ ์ํ๋ฉด public์)
- private: ์์ํด๋์ค์์ ์ฌ์ฉ ๋ถ๊ฐ๋ฅ, ํด๋น ํด๋์ค ๋ด์์๋ง ์ฌ์ฉ ๊ฐ๋ฅ (#์ผ๋ก ํ๊ธฐํ๋ฉด privated์)
- protected: ์์ ํด๋์ค์์ ์ ๊ทผ ๊ฐ๋ฅํ์ง๋ง, ํด๋์ค ์ธ์คํด์ค๋ก๋ ์ฐธ์กฐ ๋ถ๊ฐ๋ฅ
class Car4{
name: string="car";
color: string;
constructor(color: string){
this.color=color;
}
start(){
console.log("start");
}
}
class Bmx extends Car4{
constructor(color:string){
super(color);
}
showName(){
console.log(super.name);
}
}
readonly ํค์๋
- ํด๋น ๋ณ์ ์์ ๋ถ๊ฐ๋ฅ
- ์์ ๊ฐ๋ฅํ๊ฒ ํ๋ ค๋ฉด constructor๋ด๋ถ์์ ํด๋น ์์
์ ๊ฐ๋ฅํ๊ฒ ํด์ฃผ๋ฉด ๋จ
- static์ฌ์ฉํ๋ฉด, ์ ์ ๋ฉค๋ฒ ๋ณ์๋ฅผ ๋ง๋ค ์ ์์ -> this๊ฐ ์๋ ํด๋์ค ๋ช
์ ์ ์ด์ค
class Car5{
readonly name:string="car";
color: string;
static wheels=4;
constructor(color: string, name){
this.color=color;
this.name=name;
}
start(){
console.log("start");
console.log(Car5.wheels);
}
}
class Bmx2 extends Car5{
constructor(color:string, name){
super(color, name);
}
showName(){
console.log(super.name);
console.log(Car5.wheels);
}
}
์ถ์ ํด๋์ค(abstract)
- property๋ ๋ฉ์๋์ ์ด๋ฆ๋ง ์ ์ธํด์ฃผ๊ณ , ๊ตฌ์ฒด์ ์ธ ๊ธฐ๋ฅ์ ์์๋ฐฉ๋ ์ชฝ์์ ๊ตฌํ
- ์ถ์ ํด๋์ค๋ new์ด์ฉํ์ฌ ๊ฐ์ฒด ๋ง๋ค ์ ์์ -> ์์์ ํตํด์๋ง ์ฌ์ฉ ๊ฐ๋ฅ
- ์ถ์ ํด๋์ค ๋ด๋ถ์ ์ถ์ ๋ฉ์๋๋ ๋ฐ๋์ ์์๋ฐ์ ์ชฝ์์ ๊ตฌ์ฒด์ ์ธ ๊ตฌํ์ ํด์ฃผ์ด์ผ ํจ
abstract class Car6{
color: string;
constructor(color: string){
this.color=color;
}
start(){
console.log("start");
}
abstract doSomething():void;
}
class Bmw6 extends Car6{
constructor(color: string){
super(color);
}
doSomething(){
alert(3);
}
}