alswlfl 2023. 1. 3. 15:37

ํด๋ž˜์Šค

  • ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ๋Š” ๋ฉค๋ฒ„ ๋ณ€์ˆ˜๋Š” ๋ฏธ๋ฆฌ ์„ ์–ธํ•ด์ฃผ์–ด์•ผ ํ•จ
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);
  }
}