hifiveのクラスモジュール紹介(その6)「クラス変数の定義」
JavaScript(ECMAScript5)ではクラスを作成することができません。ECMAScript2015になって、ようやくクラスを使えるようになりました。しかしレガシーなブラウザでは実装されていないため、Babelのようなライブラリを使ってコードを変換するのが一般的です。
JavaScriptではprototypeやdefinePropertyなどを使ってクラス(的なもの)を実装しますが、hifiveではそういった面倒な仕組みを意識することなくクラスを実装できるモジュールを開発しました。この機能は1.3.1以降で利用できます。
今回はクラス変数の使い方について紹介します。
ベースになるクラスについて
ベースになるクラスは id というフィールドを持っていることとします。このidはクラス変数として定義された値を返します。
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 HelloClass = h5.cls.RootClass.extend(function (super_) { | |
var id = 0; | |
return { | |
// クラス名(完全修飾名) | |
name: 'HelloClass', | |
// クラスのフィールド定義 | |
field: { | |
_id: null | |
}, | |
accessor: { | |
id: { | |
get: function() { | |
return id; | |
}, | |
set: function(i) { | |
id = i; | |
} | |
} | |
}, | |
// クラスのメソッド定義 | |
method: { | |
constructor: function (params) { | |
// 親クラスのコンストラクタ呼び出し | |
super_.constructor.call(this); | |
id++; | |
} | |
} | |
}; | |
}); |
インスタンスが作られる度に id がインクリメントされていきます。そのため、この HelloClass のインスタンスが呼ばれる度にインスタンスのidの値が変わる仕組みです。
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 hello1 = Hello.HelloClass.create(); | |
hello1.id | |
// -> 1 | |
var hello2 = Hello.HelloClass.create(); | |
hello2.id | |
// -> 2 |
そして、このidはクラス変数として定義していますので、インスタンス全体で共通管理されます。例えばあるインスタンスでidを書き換えてみます。
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
hello2.id = 10; |
そうすると、別なインスタンスの値も書き換わります。
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
hello1.id | |
–> 10 |
この id はクラス内のスコープで管理される変数なので、書き換える仕組みを用意しなければ外部から書き換えられることなく安全に利用できるようになります。目的に応じて使ってみてください。
今回のコードはJSFiddleにアップロードしてあります。実装時の参考にしてください。
変数のスコープを適切に管理すれば、クラス設計とその利用がより簡単になることでしょう。ぜひhifiveのクラスモジュールを使いこなしてください。
コメントは受け付けていません。