2012.04.12 追記・修正。
インスタンスごとに固有の変数をインスタンスメンバ、インスタンスで共有される変数を静的メンバという。
静的メンバの実装方法はいくつかある。コンストラクタにプロパティを設定する方法は下記のようになる[1]。
// 関数オブジェクト var F = function (value) { this.value = value; }; // クラスのプロパティ F.classValue = 'CLASS VALUE'; F.showClassValue = function () { return 'This is CLASS VALUE'; } // インスタンプロパティ F.prototype.showValue = function () { return 'This is ' + this.value; } var ins1 = new F('Hoge'); var ins2 = new F('Foo'); var ins3 = new F('Bar'); ins1.showValue(); // This is Hoge ins2.showValue(); // This is Foo ins3.showValue(); // This is Bar F.classValue; // CLASS VALUE F.showClassValue(); // This is CLASS VALUE
[1] JavaScriptの関数はオブジェクトなのでプロパティを追加できる。
No comments yet.
改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。