Angular, TypeScript

TypeScript - Getter / Setter Methods

IT여행 2021. 12. 18. 11:02

TypeScript 

1)  Getter / Setter Methods

 

File Person.ts

class Person{

 private first: string;
 private second: string;
 
 ... ...
 
 
 public get First(): string{
  return this.first;
 }
 
 public set First(one: string): void {
  this.first= one;
 }

}

 

위 코드 를 활용해보자

 

let myPerson = new Person("Tom", "Jane");

 

myPerson.setFirst("Jack");

conlose.log(myPerson.getFirst());

 

TypeScript 

2) Accessors - Get / Set 

 

File Person.ts

class Person{

 private _first: string;               
 private _second: string;
 
 ... ...
 
 
 public get First(): string{
  return this._first;
 }
 
 public set First(value:string): {          // void를 포함하여 리턴타입 자체가 없다. 
  this._first= value  
 }

}

 

let myPerson = new Person("Tom", "Jane");

 

myPerson.first("Jack");    ------------------> set

conlose.log(myPerson.first());      --------->get

 

 

class Person{

 private x: string;               
 private y: string;
 
 ... ...
 
 
 public get first(): string{
  return this.x;
 }
 
 public set first(value:string): {          // void를 포함하여 리턴타입 자체가 없다. 
  this.x= value  
 }

}

 

et myPerson = new Person("Tom", "Jane");

 

myPerson.first("Jack");    ------------------> set

conlose.log(myPerson.first());      --------->get

 

 

위에코드를 refactoring 리팩토링해서 아래에 적어보면 다음과 같다. 

class Person{

 private _first: string;            // 초기이름을 _first로 이름 재정의     
 private _second: string;
 
 ... ...
 
 
  get first(): string{             // 차이점: public 은 삭제
  return this._first;
 }
 
  set first(value:string): {       // void를 포함하여 리턴타입 자체가 없다. 
  this._first= value;  
 }

}

 

get / set accessors 는 ES5이상에서 지원된다.

그래서 컴파일하기위해 compiler flag인 --target ES5 를 다음과 같이 붙여줘야 한다. 

ex)

C:/ tsc --target ES5 --noEmitOnError Person.ts