JavaScript クラス(class)superキーワード
例
例
以下の例で作成したクラス "サンプル" は、super を使って親クラス "Site" のコンストラクタを呼び出します:
class Site {
constructor(name) {
this.sitename = name;
}
present() {
return '私は' + this.sitename;
}
}
class サンプル extends Site {
constructor(name, age) {
super(name);
this.age = age;
}
show() {
return this.present() + 'が好きです。それは' + this.age + '年に設立されました。';
}
}
let noob = new サンプル("サンプル", 5);
document.getElementById("demo").innerHTML = noob.show();
試してみる »
定義と用法
super キーワードは、オブジェクトの親オブジェクト上の関数にアクセスして呼び出すために使用されます。
コンストラクタで使用する場合、super キーワードは単独で出現し、this キーワードを使用する前に使用しなければなりません。super キーワードは親オブジェクト上の関数を呼び出すためにも使用できます。
構文
super(arguments); // 调用父构造函数 super.parentMethod(arguments); // 调用父方法
技術詳細
| JavaScript バージョン: | ECMAScript 2015 (ES6) |
ブラウザサポート
super は ECMAScript6 (ES6) の機能です。
現在、すべての主要ブラウザが ES6 (JavaScript 2015) をサポートしています。
| Chrome | Edge | Firefox | Safari | Opera |
| Yes | Yes | Yes | Yes | Yes |
Internet Explorer 11 またはそれ以前のバージョンの IE は super キーワードをサポートしていません。
その他の例
クラス内で super を使用する:
例
class Polygon {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
sayName() {
return 'Hi, I am a ' + this.name + '.';
}
get area() {
return this.height * this.width;
}
set area(value) {
this._area = value;
}
}
class Square extends Polygon {
constructor(length) {
//ここでは、親クラスのコンストラクタを呼び出します。
//Polygon の height、width は
super(length, length);
this.height; //super の後に置く必要があります。そうしないと ReferenceError が発生します。
//注意:派生クラスでは、'this' を使用する前に、まず super() を呼び出さなければなりません。
//これを無視すると、参照エラーが発生します。
this.name = 'Square';
}
}
試してみる »
super を使用して親クラスの静的メソッドを呼び出す:
例
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'
試してみる »
その他の拡張
JavaScript クラス(class)