class Animal {
constructor(name) {
this.speed = 0;
this.name = name;
}
run(){}
}
class Rabbit extends Animal{
}
let rabbit = new Rabbit('rab');
상속받은 클래스가 객체를 생성하면 상위객체의 constructor가 반드시 호출되므로 constructor매개변수에 맞게 전달해야 한다.
extends는 프로토타입객체를 기반으로 동작하도록 되어있다.
Rabbit.prototype[[Prototype]] = Animal.prototype;로 되어
Rabbit.prototype에서 메서드를 찾지 못하면 Animal.prototype에서 메서드를 찾는다.
rabbit.run(); 속성접근자의 검색순서
1. rabbit객체에 run프로퍼티가 있는지 검사, 없다면
2. Rabbit.prototype객체에 run이 있는지 검사, 없다면
3. Animal.prototype객체에 run이 있는지 검사
4. 있다면 rabbit객체에 run메소드를 연결후 호출한다.
예를 들어 Date.prototype.[[Prototype]]=Object.prototype;
되어있어 date객체는 Object.prototype객체에 정의되어있는 메소드를 사용할 수 있는 것이다.
function f(phrase) {
return class {
sayHi() { alert(phrase) }
}
}
class User extends f("Hello") {}
new User().sayHi(); // Hello
extends뒤에 위와같이 표현식을 사용할 수 있다.
class Rabbit extends Animal {
stop() {
super.stop(); // 부모 클래스의 stop을 호출해 멈추고,
this.hide(); // 숨습니다.
}
}
임의메소드가 오버라이딩되어있거나 상위객체의 메소드를 호출할때는 위와 같이 super키워드를 사용하면 된다.
화살표함수에서는 super키워드를 사용할 수 없다.