2016-12-28 68 views
0

我試圖訪問一個類的靜態屬性,而不使用該類的實例來這樣做。我試圖修改this post中的方法,但無濟於事。我得到的全部是test.getInstanceId is not a function訪問JavaScript類的靜態屬性而不使用類的實例

根據我如何創建類(如下),我該怎麼做? 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

感謝RobG,以下作品的代碼。它通過使用test.currentInstance = ...將變量設置爲公開。這裏是the working fiddle

當檢查對象test時,現在的公共變量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的:https://jsfiddle.net/gt0wd8hp/10/

+0

myTest是一個測試的實例,爲了能夠使用它,我需要對它進行全局引用。任何方式來獲得沒有實例myTest的靜態? – mseifert

+0

不要這樣想。你可以做這樣的事情? http://stackoverflow.com/a/1535687/554021 – Baruch

+0

是的,這是我發佈在問題中的同一鏈接。我需要保持我的類定義在當前格式。如果我無法找到訪問靜態的外部方法,那麼我必須保留對類的實例的引用。 – mseifert