[TypeScript] class 키워드

JoGabi·2022년 3월 4일
0

TypeScript

목록 보기
4/8
post-thumbnail

TypeScript 로 개발할 때 class 로 많이 만드는 형태를 많이 사용한다.
그중 4개의 키워드인 public parivate protected static 에 대해 공부해 보았다.

일부는 자바스크립트에서 사용불가 하다.

1) public

public 키워드 : 생성되는 모든 object들은 name 속성을 가져다 쓰고 수정이 가능하다.
하지만 public 키워드는 없어도 상관없다 (생략되어있음 강제부여)

constructor 존재의 차이?

constructor(){} 는 생략 가능 하다.
하지만 constructor 파라미터값을 지정하는 경우가 있기 때문이다 !!!

class People {
  public name = "gabi"; 
  constructor(a) {
    this.name = a;
  }
}
let user1 = new People("jojo");
user1.name = "mimi";

class PointMap {
  public position = "seoul";
  constructor(d) {
    this.position = d;
  }
}
let pos = new PointMap("incheon");
pos.position = "new incheon";

2) private

public 과 비슷하다 하지만 private 붙이게 되면 자식들이 수정을 할 수가 없다 . class 안에서만 수정이 가능하다.

class PointMap {
  private position = "seoul";
  constructor(d) {
    this.position = d;
  }
}

let pos = new PointMap("incheon");
pos.position = "new incheon"; //에러남 : 수정할 권한이 없다.

'Derived' 클래스가 기본 클래스 'Base'을(를) 잘못 확장합니다.
'x' 속성은 'Base' 형식에서 private이지만 'Derived' 형식에서는 그렇지 않습니다.ts(2415)

class Base {
  private x = 0;
}
class Derived extends Base {
  x = 1;
}

다른예제

locationPosition,locationArrival 속성 추가를 해보자 타입지정도 해보자

locationArrival 은 앞에 private 를 붙였기 때문에 수정이불가능
하지만 class {} 안에서는 수정,사용가능

class PointMap {
  locationPosition: string;
  private locationArrival: string = "incheon";
  constructor(d) {
    this.locationPosition = this.locationArrival + "->" + d;
  }
}

let userPosition = new PointMap("seoul");
console.log(userPosition); //PointMap {locationArrival: 'incheon', locationPosition: 'incheon->seoul'}

class locationArrival을 밖에서 수정이 가능하려면 ?

react 에서 은근히 자주 쓰인다.

class PointMap {
  locationPosition: string;
  private locationArrival: string = "incheon";
  constructor(d) {
    this.locationPosition = this.locationArrival + "->" + d;
  }

  changeLocationArrival() {
    this.locationArrival = "test";
  }
}

let userPosition = new PointMap("seoul");
userPosition.changeLocationArrival();

console.log(userPosition); // PointMap {locationArrival: 'test', locationPosition: 'incheon->seoul'}

축약어 제공 자동 속성 추가

얖에 public 을 붙이면 props 선언을 하지 않아도 props 속성 기입됨

class Person {
  constructor(public props : string) {}
}
let test = new Person("gggg");
console.log(test); //Person {props: 'gggg'}

3) protected

private 붙이면 class{} 안에서만 사용가능
protected extends 된 class{} 에서도 사용가능


class Greeter {
  public greet() {
    console.log("Hello, " + this.getName());
  }
  protected getName() {
    return "hi";
  }
}

class SpecialGreeter extends Greeter {
  public howdy() {
    console.log("Howdy, " + this.getName());
  }
}
const g = new SpecialGreeter();
g.greet(); // Hello, hi
g.getName(); //'getName' 속성은 보호된 속성이며 'Greeter' 클래스 및 해당 하위 클래스 내에서만 액세스할 수 있습니다.ts(2445)

4) static

자식들이 물려받지못하고 부모만 사용할 수 있게 함

class User {
  static a = 10;
  private  static a = 10; // 가능, 둘의 효과를 동시에 적용함
  b = 20;
}
let result = new User()
console.log(result); //User {b: 20}
console.log(User.a); // 10 부모만 부를 수 있음
class MyClass {
  static x = 0;
  static printX() {
    console.log(MyClass.x);
  }
}

console.log(MyClass.x);
MyClass.printX();

어떻게 활용 할까?

class User {
  static job = "programmer"
  con = User.job + '입니다' // static 붙으면 무조건 부모에서만 선택할 수 있음

}

let gabi = new User()
console.log(gabi);

static 값 변경하기

class User {
  static job = "programmer"
  con = User.job + '입니다' // static 붙으면 무조건 부모에서만 선택할 수 있음
}
User.job = 'ts' // constructor 의 파라미터로 받아도 되지만 gabi2 만 job을 변경하고 싶을때 사용

let gabi2 = new User()
console.log(gabi2);

화면에 위치가 랜덤인 박스 출력하기


class Box {
  constructor(public a: number, public b: number, public c: string) {}
  add() {
    let randomNum = Math.random();

    let box = `<div style="width:${this.a}px;height:${
      this.b
    }px;background-color:${this.c};top:${randomNum * 400}px;left:${
      randomNum * 400
    }px;position:relative" >${randomNum}</div>`;

    document.body.insertAdjacentHTML("beforeend", box);
  }
}

let square = new Box(30, 30, "gray");

square.add();
square.add();
square.add();
square.add();
profile
서울에서 프론트엔드 개발자로 일하고 있는 Gabi 입니다. 프론트엔드: Javascript, React, TypeScript 에 관심이 있습니다.

0개의 댓글

관련 채용 정보