클래스가 어떠한 다른 클래스의 기능을 가져다가 사용할 때 상속받아 사용한다.

 

private, protected 키워드를 이용해서 각자의 영역에서 서로의 영역을 오염시키지 않도록 조심하는것이 중요

 

예제

TS 파일

class Parent {
  constructor(protected _name: string, private _age: number){}

  public print(): void {
    console.log(`이름은 ${this._name} 이고, 나이는 ${this._age} 입니다.`);
  }

  protected printname(): void {
    console.log(this._name, this._age);
  }
}

const p331 = new Parent('Mark', 22);
p331.print();

// 상속
class Child extends Parent {

  public _name = "Mark jr";

  public gender = "male";

  constructor(age: number){
    // super를 최상단에 위치해야 부모의 것들을 접근 가능하다
    super('생성자 재정의', age);
    this.printname();
  }
}

// Child에 별다른 선언을 하지 않았을 경우에는 Parent 생성자를 그대로 사용한다.
// const c = new Child("Son", 4);
// CHild에서 재정의
const c = new Child(33);
c.print();
c.gender

컴파일된 JS 파일

"use strict";
class Parent {
    constructor(_name, _age) {
        this._name = _name;
        this._age = _age;
    }
    print() {
        console.log(`이름은 ${this._name} 이고, 나이는 ${this._age} 입니다.`);
    }
    printname() {
        console.log(this._name, this._age);
    }
}
const p331 = new Parent('Mark', 22);
p331.print();
// 상속
class Child extends Parent {
    constructor(age) {
        // super를 최상단에 위치해야 부모의 것들을 접근 가능하다
        super('생성자 재정의', age);
        this._name = "Mark jr";
        this.gender = "male";
        this.printname();
    }
}
// Child에 별다른 선언을 하지 않았을 경우에는 Parent 생성자를 그대로 사용한다.
// const c = new Child("Son", 4);
// CHild에서 재정의
const c = new Child(33);
c.print();
c.gender;

 

화면 확인

'프론트엔드 > TypeScript' 카테고리의 다른 글

제네릭  (0) 2021.06.22
Abstract Class  (0) 2021.06.21
class - singleton 패턴  (0) 2021.06.21
class - Static Properties 와 Method  (0) 2021.06.21
class - index Signatures  (0) 2021.06.21

+ Recent posts