2016-12-28 23 views
0

クラスのインスタンスを使用せずにクラスの静的プロパティにアクセスしようとしています。私は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()); 
+1

また、 'console.log(myTest.getInstanceId())'ではなく、 https://jsfiddle.net/gt0wd8hp/10/ – Baruch

+0

@Baruch 'new test()'は 'test'クラスのインスタンスを生成します。このようなクラスを定義することで、クラスのインスタンスからアクセスできる静的変数を持つことができます。 'myTest'は' test'のインスタンスであり、それを使用できるようにするには、私はそれをグローバルに参照する必要があります。私はそれが必要ではないと望んでいます。 – mseifert

+0

さて、私はそれが理にかなっていないことを認識したら、そのコメントを削除しました。 – Baruch

答えて

0

感謝を。 test.currentInstance = ...を使用して変数をパブリックに設定します。ここにはthe working fiddleがあります。

オブジェクトtestを検査すると、現在公開されているvar currentInstanceは、testファンクションプロトタイプの外に「生きている」ように見えますが、これは実現できませんでした。

私はではありません。は指摘している命名規則を訂正しました。これはテストの代わりにテストでなければなりません。

test = (function() { 
    test.currentInstance = undefined; 

    function test() { 
    this.id = 0; 
    test.currentInstance = this; 
    } 


    test.prototype.setId = function(id) { 
    this.id = id; 
    } 

    return test; 
})(); 



var myTest = new test(); 
myTest.setId(1); 
console.log(myTest.id) 
console.log(test.currentInstance.id); 
0

私のコメントが示すように、あなたはtest.getInstanceId()代わりのmyTest.getInstanceId()

var test = (function() { 
    var currentInstance; 
    /* This won't work 
    function getInstanceId(){ 
     return currentInstance.id; 
    } 
    */ 

    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(myTest.getInstanceId()); 

FID使用している:RobG、作品の以下のコードにhttps://jsfiddle.net/gt0wd8hp/10/

+0

myTestはtestのインスタンスであり、それを使用できるようにするためには、グローバル参照を保持する必要があります。インスタンスmyTestなしで静的に取得する方法はありますか? – mseifert

+0

そうは思わない。あなたはおそらくこのようなことをすることができますか? http://stackoverflow.com/a/1535687/554021 – Baruch

+0

はい、これは私が質問に投稿したのと同じリンクでした。私はクラス定義を現在の形式に保つ必要があります。静的にアクセスする外側の方法が見つからない場合は、そのクラスのインスタンスへの参照を保持する必要があります。 – mseifert

関連する問題