class Rectangle {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
get area() {
return this.height * this.width;
}
set area(value) {
this.height = this.width = Math.sqrt(value);
}
}
class Square extends Rectangle {
constructor(length) {
this.height; // ReferenceError になります。super を先に呼び出さなければなりません!
// length の値で親クラスの constructor を呼びます。
// Rectangle の width と height になります。
super(length, length);
// Note: 'this' を使う前に super() をコールしなければなりません。
// でないと reference error になります。
this.name = 'Square';
}
}
親のコンストラクターを読んで上書きできる
class Rectangle {
constructor() {}
static logNbSides() {
return 'I have 4 sides';
}
}
class Square extends Rectangle {
constructor() {}
static logDescription() {
return super.logNbSides() + ' which are all equal';
}
}
Square.logDescription(); // 'I have 4 sides which are all equal'
親の関数をstaticメソッド内部でsuperを通じて呼び出すことができる
var obj1 = {
method1() {
console.log('method 1');
}
}
var obj2 = {
method2() {
super.method1();
}
}
Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // logs "method 1"
obj2.method1() // これでも呼べる
prototypeのメソッドをsuperを使うことで呼び出すことができる。
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/super
static キーワードは、クラスに静的メソッドを定義します。静的メソッドはクラスのインスタンスから呼び出されません。その代わりに、静的メソッドはクラスそのものから呼び出します。これらは多くの場合、オブジェクトの生成や複製を行う関数などの、ユーティリティ関数です。
インスタンスからはよべない。
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Classes/static