Dragon's eye でやってた継承を作る便利関数はこんなの。
function inherit( funcSubClass, funcSuperClass ) {
funcSubClass.prototype = new funcSuperClass;
}
まあ! とってもシンプルw
このシンプルさが好きだったってのもあるけど、これっていろいろダメ(^^;;;
で、ちゃんと調べて考えて、こんくらい書かないとダメだと分かった。
function inherit( funcSubClass, funcSuperClass ) {
var funcTemp = new Function();
funcTemp.prototype = funcSuperClass.prototype;
funcSubClass.prototype = new funcTemp;
funcSubClass.prototype.constructor = funcSubClass;
funcSubClass.prototype.base = function () {
var funcOrigBase = this.base;
this.base = funcSuperClass.prototype.base || null;
funcSuperClass.apply( this, arguments );
this.base = funcOrigBase;
if( this.constructor == funcSubClass )
delete this.base;
}
}
これを使って、継承を書くとこんな感じ
function BaseHoge() {
:
:
}
function DerivedHoge() {
this.base();
:
:
}
inherit( DerivedHoge, BaseHoge );
これなら Dragon's eye での1世代しか継承できないなんちゃって継承ではなく、何世代継承してもちゃんと動く継承が作れる。
にしても。
派生クラスのコンストラクタで親のコンストラクタを明示的に呼び出さないといけない(上のコードで this.base(); の部分)がダサくてヤダ。
暗黙に呼び出されるようにするにはどうしたらええのん?
いろいろ考えてるけどまだ解は見つからずorz
0 件のコメント:
コメントを投稿