概要
javascriptでサブクラスの定義をします。
javascriptのオブジェクトはクラスのプロトタイプからプロパティを継承します。
継承した状態のサンプルを書いてみます。
[js]
//テスト用クラス
function Mainclass() {}
var SubClass = (function () {
SubClass.prototype = new Mainclass();
SubClass.prototype.constructor = SubClass;
});
//オブジェクトを生成してみる
let MainObj = new Mainclass();
let SubObj = new SubClass();
//生成したオブジェクトを調べる
console.log(MainObj);
console.log(SubObj);
//MainObjにSubObjのコンストラクタのprototypeが存在するか
console.log(MainObj instanceof Mainclass);
console.log(MainObj instanceof SubClass);
console.log(SubObj instanceof Mainclass);
console.log(SubObj instanceof SubClass);
[/js]
出力結果は次のようになります。
[js]
Object { }
Object { }
true
false
false
false
[/js]
後半の2行の出力結果は、サブクラスのプロトタイプオブジェクトをメインクラスのプロトタイプオブジェクトを継承していない為です。