Javascript で静的変数を作成するにはどうすればいいですか?
ベストアンサー1
クラスベースの静的に型付けされたオブジェクト指向言語(Java、C++、C# など)の経験がある場合、インスタンスではなく「型」に関連付けられた変数またはメソッドを作成しようとしているものと想定します。
コンストラクター関数を使用した「古典的な」アプローチを使用した例は、基本的な OO JavaScript の概念を理解するのに役立つかもしれません。
function MyClass () { // constructor function
var privateVariable = "foo"; // Private variable
this.publicVariable = "bar"; // Public variable
this.privilegedMethod = function () { // Public Method
alert(privateVariable);
};
}
// Instance method will be available to all instances but only load once in memory
MyClass.prototype.publicMethod = function () {
alert(this.publicVariable);
};
// Static variable shared by all instances
MyClass.staticProperty = "baz";
var myInstance = new MyClass();
staticProperty
MyClassオブジェクト(関数)で定義され、作成されたインスタンスとは関係がないため、JavaScriptは関数を次のように扱います。一級品オブジェクトなので、関数にプロパティを割り当てることができます。
更新: ES6では、クラスを宣言するキーワードを通じてclass
。これは、既存のプロトタイプベースの継承に対する構文糖です。
のstatic
キーワードクラス内の静的プロパティまたはメソッドを簡単に定義できます。
上記の例を ES6 クラスで実装したものを見てみましょう。
class MyClass {
// class constructor, equivalent to
// the function body of a constructor
constructor() {
const privateVariable = 'private value'; // Private variable at the constructor scope
this.publicVariable = 'public value'; // Public property
this.privilegedMethod = function() {
// Public Method with access to the constructor scope variables
console.log(privateVariable);
};
}
// Prototype methods:
publicMethod() {
console.log(this.publicVariable);
}
// Static properties shared by all instances
static staticProperty = 'static value';
static staticMethod() {
console.log(this.staticProperty);
}
}
// We can add properties to the class prototype
MyClass.prototype.additionalMethod = function() {
console.log(this.publicVariable);
};
var myInstance = new MyClass();
myInstance.publicMethod(); // "public value"
myInstance.additionalMethod(); // "public value"
myInstance.privilegedMethod(); // "private value"
MyClass.staticMethod(); // "static value"