在没有实例化的情况下访问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);
但我想确保它是正确的这样做。
答案 0 :(得分: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