我試圖訪問一個類的靜態屬性,而不使用該類的實例來這樣做。我試圖修改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());
另外,是不是'console.log(myTest.getInstanceId())'而不是? https://jsfiddle.net/gt0wd8hp/10/ – Baruch
@Baruch'new test()'會創建''''''test'的一個實例。像這樣定義類允許我有一個靜態變量,可以從類的一個實例中訪問。 'myTest'是'test'的一個實例,爲了能夠使用它,我需要保留一個全局引用,我希望我不需要這樣做。 – mseifert
是的,一旦我意識到它沒有任何意義,我刪除了該評論。 – Baruch