클래스는 다른 클래스의 property와 method들을 재사용 할 수 있음. 이를 상속이라고함.
property와 method를 상속받은 클래스를 child class라고 하고 상속해준 클래스를 parent class라고함.
자바스크립트는 프로토타입 상속으로 상속을 구현했는데 이거는 자바나 C# 같은 일반적으로 생각하는 상속과는 다른거임.
아래처럼 Person클래스가 있다고 했을때
class Person {
constructor(private firstName: string, private lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
describe(): string {
return `This is ${this.firstName} ${this.lastName}.`;
}
}
위 클래스를 상속받으려면 extend 키워드를 사용하면됨. 아래는 Employee클래스를 상속받은 Person 클래스임.
따라서 Employee클래스는 Person클래스의 child 클래스고 Person클래스는 Employee클래스의 parent 클래스임.
class Employee extends Person {
//..
}
위의 Person 클래스가 firstName과 lastName을 초기화 해주는 생성자를 가지고 있기 떄문에 Employee클래스에서도 부모클래스의 생성자를 불러서 이 property들을 초기화 시켜줘야함.
부모 클래스의 생성자를 자식 클래스에서 호출하려면 super()를 사용하면됨.
class Employee extends Person {
constructor(
firstName: string,
lastName: string,
private jobTitle: string) {
// call the constructor of the Person class:
super(firstName, lastName);
}
}
let employee = new Employee('John','Doe','Front-end Developer');
employee클래스가 Person클래스의 property들과 멤소드들을 상속받았기 때문에 아래와 같이 getFullName()과 describe()메소드들을 employee 객체에서도 사용할 수 있음.
let employee = new Employee('John', 'Doe', 'Web Developer');
console.log(employee.getFullName());
console.log(employee.describe());
employee 객체의 employee.describe() 메소드를 호출할때 Person 클래스의 describe() 메소드가 실행됨.
만약에 Employee 클래스가 자신만의 describe() 메소드를 가지게 하고 싶으면 아래처럼 정의해주면됨.
class Employee extends Person {
constructor(
firstName: string,
lastName: string,
private jobTitle: string) {
super(firstName, lastName);
}
describe(): string {
return super.describe() + `I'm a ${this.jobTitle}.`;
}
}
위의 describe()에서는 부모의 describe() 메소드도 super.describe()를 통해서 불러주고 있음.
이제 employee객체의 describe() 메소드를 호출하면 employee객체의 describe()메소드가 실행되는것임.
let employee = new Employee('John', 'Doe', 'Web Developer');
console.log(employee.describe());
// Output : This is John Doe.I'm a Web Developer.
extends 키워드를 사용해 다른 클래스를 상속할 수 있음super()를 이용해 부모 클래스의 생성자를 호출할 수 있음. 또한 super().methodInParentClass() syntax를 통해서 부모 클래스의 메소드를 자식 클래스에서 사용가능함