class

y0ung·2020년 11월 18일
0

TypeScript

목록 보기
6/12
post-thumbnail

class

javascript

//javascript
class Person {
  constructor(name, age){
    console.log('생성 되었습니다.');
    this.name = name;
    this.age = age;
  }
}

let profile = new Person('olive',26);

typescript

class Person {
   name:string;
   age:number; 
  
  constructor(name:string,age:number){
    console.log('생성 되었습니다.');	
    this.name = name;
    this.age = age
  }
}

prototype?

private & public

class Person {
  private name:string; 
  public age:number; 
  
  constructor(name:string,age:number){
 	// ...
  }
}
  • private : 해당 클래스 안에서만 사용할수 있다.
  • public : 클래스 밖에서도 사용할수 있다.

readonly

클래스에서 접근은 가능하지만 값이 변하지 않게 하고 싶을경우에는readonly를 사용


// typescript
class Developer {
  readonly name: string;
  constructor(theName: string){
    this.name = theName;
  }
}

let olive = new Developer('olive');
olive.name = '0live" // error! name is readonly

이처럼 readonly를 사용하면 constructor() 함수에 초기 값 설정 로직을 넣어줘야 하므로 인자에 readonly 키워드를 추가해서 코드를 줄일 수 있습니다.


class Developer {
  readonly name: string;
  constructor(readonly name: string) {
  }
}

profile
어제보다는 오늘 더 나은

0개의 댓글