【发布时间】:2022-06-29 23:06:44
【问题描述】:
有没有办法保持实例的静态计数
class Myclass {
static s = 0; // static property
p = 0; // public field declaration
constructor() {
console.log("new instance!")
this.s += 1;
this.p += 1;
console.log(this.s, this.p);
this.i = this.s; // instance property
}
}
let a = new Myclass();
console.log(a.s, a.p, a.i)
let b = new Myclass();
console.log(b.s, b.p, b.i)
输出
new instance!
NaN 1
NaN 1 NaN
new instance!
NaN 1
NaN 1 NaN
或者是在类之外更好地跟踪实例,例如一个数组,例如
var instances = new Array();
class Myclass {
constructor(name) {
console.log("new instance!")
this.name = name;
this.i = instances.length;
instances.push(this);
}
}
let a = new Myclass('a');
console.log(instances.length, a.i)
let b = new Myclass('b');
console.log(instances.length, b.i)
console.log( instances[1].name )
有预期的输出
new instance!
1 0
new instance!
2 1
b
【问题讨论】:
-
"有没有办法保持静态计数" - 是的,但是你需要参考
static属性usingMyclass.s, notthis.s。 “或者在课堂之外更好地跟踪实例” - 是的,绝对!您甚至不应该将它们从构造函数推送到该数组中,而应使用单独的工厂函数。
标签: javascript class properties