継承と super
実践JavaScript / 全 5 枚
実践JavaScript - 継承と super
extends で受け継ぎ、差分だけを書く
注目作品は、ふつうの作品にキャッチコピーが1つ増えただけのものです。extends を書くと Work の持ち物をそのまま受け継げるので、書き足すのは増えたぶんと、変えたいメソッドだけになります。
title と tag を this に置く処理は1行も書いていません。親に任せて、増えた copy だけを自分で置いています。
super(title, tag) が親の constructor、super.label() が親のメソッドの呼び出しです。
class FeaturedWork extends Work {
constructor(title, tag, copy) {
super(title, tag);
this.copy = copy;
}
label() {
return "注目 " + super.label();
}
}1 / 5
← → キーでも送れます