簡體   English   中英

Javascript訪問原型中的變量而不實例化

[英]Javascript access variables in prototype without instantiating

在沒有實例化的情況下訪問javascript類中的變量是不好的做法嗎?

例如:

var Test = function(){
  this.tests.push("Something");
}
Test.prototype.tests = [];

var test = new Test();

console.log(Test.prototype.tests); //Is this okay to do? Obviously I can use test.test here, but this is a poor example of why I am wanting to do this; it merely shows my question.

我遇到過一個我只有id的實例,我想使用該類為我獲取正確的自身實例: Test.prototype.getByID(id); 但我想確保這樣做是正確的。

您可以利用JavaScript中的閉包並執行以下操作( jsfiddle )。 這樣做的好處是可以將您的“測試列表”設為私有,這樣就不會被搞亂,而且您不必訪問原本感覺有點奇怪的prototype

var Test = (function() {
    var tests = {};

    var Test = function(id){
        tests[id] = this;
        this.id = id;
    }

    Test.getByID = function(id) {
        return tests[id];
    }

    return Test;
}());

var test1 = new Test(1);
var test2 = new Test(2);

var test2_2 = Test.getByID(2);

alert( test1 === test2_2 );//should be false
alert( test2 === test2_2 );//should be true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM