访问javascript类的静态属性,而不使用该类的实例
我试图访问一个类的静态属性,而不使用该类的实例。我试着用这种方法,但没有用。我得到的只是访问javascript类的静态属性,而不使用该类的实例,javascript,class,static,Javascript,Class,Static,我试图访问一个类的静态属性,而不使用该类的实例。我试着用这种方法,但没有用。我得到的只是test.getInstanceId不是一个函数 根据我创建类的方式(见下文),我如何才能做到这一点 正如我的评论所示,您使用的是test.getInstanceId()而不是myTest.getInstanceId() Fid:多亏了RobG,下面的代码才有效。它通过使用test.currentInstance=…将变量设置为公共变量。这是 当检查对象test时,现在公共的varcurrentInstanc
test.getInstanceId不是一个函数
根据我创建类的方式(见下文),我如何才能做到这一点
正如我的评论所示,您使用的是
test.getInstanceId()
而不是myTest.getInstanceId()
Fid:多亏了RobG,下面的代码才有效。它通过使用
test.currentInstance=…
将变量设置为公共变量。这是
当检查对象test
时,现在公共的varcurrentInstance
似乎在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);
另外,它不是
console.log(myTest.getInstanceId())
吗@Baruchnewtest()
将创建类的一个实例
test
。这样定义类允许我拥有静态变量,我可以从类的实例访问这些变量myTest
是test
的一个实例,为了能够使用它,我需要保留对它的全局引用,我希望我不需要这样做。是的,我在意识到它毫无意义时删除了该注释。以这种方式使用闭包的目的是创建“私有”属性。如果希望它们是公共的,则将它们公开,例如,test.currentInstance=…
。按照惯例,构造函数名称以大写字母开头,所以请测试而不是测试。@RobG-感谢您的帮助和见解。我已经发布了一个带有工作代码的答案,供任何关注我的人使用,但是如果你想发布答案,我会接受它。myTest是test的一个实例,为了能够使用它,我需要保留对它的全局引用。没有myTest实例的情况下,有什么方法可以获得静态数据?我不这么认为。你可能会这样做?是的,这与我在问题中发布的链接相同。我需要保持我的类定义的当前格式。如果我找不到访问静态的外部方法,我将不得不保留对该类实例的引用。
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());
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);