ES6에서는 자바와 같이 extends 키워드로 상속을 표현한다.
부모 클래스의 멤버를 자식 클래스가 상속 받아서 사용 가능하다.
자식 클래스와 부모 클래스 양쪽 constructor를 작성하지 않아도 인스턴스가 생성된다. (default constructor 사용)
부모 클래스에만 constructor를 작성하면, 자식 클래스의 'default 생성자'가 호출되고 부모 클래스의 constructor가 호출된다.
자식 클래스에만 constructor만 작성하면 자식 클래스의 constructor가 호출되고, 반드시 부모의 constructor를 명시적으로 호출해야한다.
자식과 부모 클래스 양쪽 constructor를 작성하면 자식 constructor가 호출되지만, 반드시 부모 constructor를 명시적으로 호출해야한다.
<script type="text/javascript">
// 상속
class Employee {
constructor(name, salary) {
console.log('부모 생성자 ========');
this.name = name;
this.salary = salary;
}
setName(name) {
this.name = name;
}
setSalary(salary) {
this.salary = salary;
}
getName() {
return this.name;
}
getSalary() {
return this.salary;
}
}
class Manager extends Employee {
constructor(name, salary, depart) {
console.log('자식생성자 =========');
super(name, salary); // 부모 생성자 명시적 호출 필수
this.depart = depart;
}
setDepart(depart) {
this.depart = depart;
}
getDepart() {
return this.depart;
}
}
var man = new Manager();
man.setName('홍길동');
man.setSalary(1000);
man.setDepart('인사');
console.log(man.getName());
console.log(man.getSalary());
console.log(man.getDepart());
</script>