クラスのインスタンスを使用せずにクラスの静的プロパティにアクセスしようとしています。私はthis postでメソッドを適用しようとしましたが、無駄です。私が得るのはtest.getInstanceId is not a function
クラスのインスタンスを使用せずにjavascriptクラスのstaticプロパティにアクセス
どのように私がこのクラスを作成しているかに基づいて、私はこれをどうやってできますか? Here is a fiddle。
test = (function() {
var currentInstance;
function test() {
this.id = 0;
currentInstance = this;
// this won 't work
this.getInstanceId = function() {
return currentInstance.id;
}
}
test.prototype.setId = function(id) {
this.id = id;
}
return test;
})();
var myTest = new test();
myTest.setId(1);
console.log(myTest.id)
console.log(test.getInstanceId());
また、 'console.log(myTest.getInstanceId())'ではなく、 https://jsfiddle.net/gt0wd8hp/10/ – Baruch
@Baruch 'new test()'は 'test'クラスのインスタンスを生成します。このようなクラスを定義することで、クラスのインスタンスからアクセスできる静的変数を持つことができます。 'myTest'は' test'のインスタンスであり、それを使用できるようにするには、私はそれをグローバルに参照する必要があります。私はそれが必要ではないと望んでいます。 – mseifert
さて、私はそれが理にかなっていないことを認識したら、そのコメントを削除しました。 – Baruch