[英]Static count of JavaScript Class instances
有沒有辦法保持實例的靜態計數
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
但不能使用this
(因為它指的是特定實例)。 而是使用類名。
class MyClass { static s = 0; // static property p = 0; // public field declaration constructor() { console.log("new instance!") MyClass.s += 1; this.p += 1; console.log(MyClass.s, this.p); this.i = MyClass.s; // instance property } } let a = new MyClass(); console.log(MyClass.s, ap, ai) let b = new MyClass(); console.log(MyClass.s, bp, bi)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.