hifiveのクラスモジュール紹介(その7)「親クラスの取得」
JavaScript(ECMAScript5)ではクラスを作成することができません。ECMAScript2015になって、ようやくクラスを使えるようになりました。しかしレガシーなブラウザでは実装されていないため、Babelのようなライブラリを使ってコードを変換するのが一般的です。
JavaScriptではprototypeやdefinePropertyなどを使ってクラス(的なもの)を実装しますが、hifiveではそういった面倒な仕組みを意識することなくクラスを実装できるモジュールを開発しました。この機能は1.3.1以降で利用できます。
今回は親クラスの取得方法について紹介します。
クラスの構造について
クラスや親クラスとしてAnimalClass、それらを継承するDogClassがあることとします。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var AnimalClass = h5.cls.RootClass.extend(function (super_) { | |
return { | |
// クラス名(完全修飾名) | |
name: 'AnimalClass', | |
// クラスのフィールド定義 | |
field: { | |
_name: null | |
}, | |
// クラスのメソッド定義 | |
method: { | |
constructor: function (params) { | |
// 親クラスのコンストラクタ呼び出し | |
super_.constructor.call(this); | |
this._name = params; | |
}, | |
hello: function() { | |
return this._name; | |
}, | |
cry: function(name, voice) { | |
return name + "'s crying voice is " + voice; | |
} | |
} | |
}; | |
}); | |
var DogClass = AnimalClass.extend(function (super_) { | |
return { | |
name: 'DogClass', | |
field: { | |
_voice: { | |
defaultValue: 'bow wow' | |
} | |
}, | |
method: { | |
constructor: function (params) { | |
super_.constructor.call(this, params); | |
}, | |
cry: function() { | |
return super_.cry(this._name, this._voice); | |
} | |
} | |
} | |
}); |
DogClassの親クラスを取得するには getParentClass
メソッドを実行します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Animal.DogClass.getParentClass() |
この返却されるクラスはAnimalClassと同じものになります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Animal.DogClass.getParentClass() === Animal.AnimalClass | |
// -> true |
今回のコードはJSFiddleにアップロードしてあります。実装時の参考にしてください。
継承している中で親クラスが何であるかを指定するケースはよくあります。そうした時には getParentClass
メソッドを活用してください。
コメントは受け付けていません。