타입스크립트 - 클래스

hwakyungChoi·2020년 9월 8일
1

클래스 정의

class User{
	constructor(name){
    	this.name = name;
    }
    write(){
    	console.log(`${this.name} is writing`)
    }
}
//ES6 클래스는 클래스 몸체에 메소드만 포함
//생성자 내부에 클래스 프로퍼티 선언 및 초기화
class User {
	name: string;
  
  constructor(name:string){
  this.name = name;
  }
  
  writing(){
    	console.log(`${this.name} is writing`)
  }
}
//타입스크립트는 클래스 몸체에 클래스 프로퍼티를 사전 선언해야 함

접근 제한자

  • 클래스 기반 객체 지향 언어가 지원하는 접근 제한자 지원 : public, protected, private
  • 접근 제한자를 생략할 시 암묵적으로 public으로 판단
class Fn{
	public x: string;
  	protected y: string;
  	private z : string;
  
  constructor(x:string, y:string,z:string){
    //접근 제한자 모두 클래스 내부에서 참조 가능
  	this.x = x;
    this.y = y;
    this.z = z;
    
  }
}

const fn = new Fn("x","y","z")
// public 접근 제한자는 클래스 인스턴스를 통해 클래스 외부 참조 가능
console.log(fn.x)
//protected 접근 제한자는 클래스 외부 참조 불가능
console.log(fn.y)
// private접근 제한자는 클래스 외부 참조 불가능
console.log(fn.z)

class fun extends Fn{
	constructor(x:string,y:string,z:string){
    	super(x,y,z)
      //public 접근 제한자는 자식클래스 내부 참조가능
      console.log(this.x)
      //protected 접근 제한자는 자식클래스 내부 참조 가능
      console.log(this.y)
      //private 접근 제한자는 자식 클래스 내부 참조 불가능
      console.log(this.z)
      
    }
}

생성자 파라미터 접근 제한자 선언

  • 접근 제한자가 사용된 생성자 파라미터는 암묵적으로 클래스 프로퍼티로 선언, 생성자 내부에서도 별도의 초기화가 없어도 암묵적으로 초기화 수행
class Foo {
  //클래스 외부에서 참조 가능

  constructor(public x: string) { }
}

const foo = new Foo('Hello');
console.log(foo);  
console.log(foo.x); 

class Bar {
//private 선언 => 클래스 내부에서만 참조 가능
  constructor(private x: string) { }
}

const bar = new Bar('Hello');

console.log(bar); 

// private이 선언되며 클래스 내부에서만 참조 가능
console.log(bar.x); 

// 생성자 파라미터에 접근 제한자 선언하지 않으면 생성자 내부에서만 유효한
// 지역변수가 되어 생성자 외부에서 참조 불가능
class Foo {
  // x는 생성자 내부에서만 유효한 지역 변수이다.
  constructor(x: string) {
    console.log(x);
  }
}

const foo = new Foo('Hello');
console.log(foo); // Foo {}

readonly 키워드

  • readonly가 선언된 프로퍼티는 재할당 금지
  private readonly MAX_LEN: number = 5;

static 키워드

  • ES6 클래스에서는 static 키워드는 정적 메소드 정의, 클래스 이름으로 호출
class Foo {
  constructor(prop) {
    this.prop = prop;
  }

  static staticMethod() {
    /*
    정적 메소드는 this를 사용할 수 없다.
    정적 메소드 내부에서 this는 클래스의 인스턴스가 아닌 클래스 자신을 가리킨다.
    */
    return 'staticMethod';
  }

  prototypeMethod() {
    return this.prop;
  }
}

// 정적 메소드는 클래스 이름으로 호출한다.
console.log(Foo.staticMethod());

const foo = new Foo(123);
// 정적 메소드는 인스턴스로 호출할 수 없다.
console.log(foo.staticMethod()); // Uncaught TypeError: foo.staticMethod is not a function
class Foo {
  // 생성된 인스턴스의 갯수
  static instanceCounter = 0;
  constructor() {
    // 생성자가 호출될 때마다 카운터를 1씩 증가시킨다.
    Foo.instanceCounter++;
  }
}

var foo1 = new Foo();
var foo2 = new Foo();

console.log(Foo.instanceCounter);  // 2
console.log(foo2.instanceCounter); // error TS2339: Property 'instanceCounter' does not exist on type 'Foo'.

추상클래스

  • 하나 이상의 추상 메소드를 포함하여 일반 메소드도 포함할 수 있음
  • 내용없이 메소드 이름과 타입만 선언된 메소드 선언할 때, abstract 키워드 사용
abstract class Animal {
  // 추상 메소드
  abstract makeSound(): void;
  // 일반 메소드
  move(): void {
    console.log('roaming the earth...');
  }
}

// 직접 인스턴스를 생성할 수 없다.
// new Animal();
// error TS2511: Cannot create an instance of the abstract class 'Animal'.

class Dog extends Animal {
  // 추상 클래스를 상속한 클래스는 추상 클래스의 추상 메소드를 반드시 구현하여야 한다
  makeSound() {
    console.log('bowwow~~');
  }
}

const myDog = new Dog();
myDog.makeSound();
myDog.move();```

1개의 댓글

comment-user-thumbnail
2021년 1월 11일

저는 private, protected가 헷갈리더라구요ㅜ 그래서 protected 클래스를, 상속 관계인 자식 class만 접근이 가능하다고 이해를 했답니담 개념확립에 도움이 될까하여 그적여보았습니다,😀

답글 달기