有沒有辦法保持實體的靜態計數
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
uj5u.com熱心網友回復:
是的,你可以使用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, a.p, a.i)
let b = new MyClass();
console.log(MyClass.s, b.p, b.i)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/497569.html
標籤:javascript 班级 特性