0

访问 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);但我想确保这样做是正确的。

4

1 回答 1

2

您可以利用 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
于 2013-07-26T23:16:01.433 回答