【问题标题】:Static count of JavaScript Class instancesJavaScript 类实例的静态计数
【发布时间】: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 属性using Myclass.s, not this.s。 “或者在课堂之外更好地跟踪实例” - 是的,绝对!您甚至不应该将它们从构造函数推送到该数组中,而应使用单独的工厂函数。

标签: javascript class properties


【解决方案1】:

是的,您可以使用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)

【讨论】:

    猜你喜欢
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-27
    • 2010-10-25
    相关资源
    最近更新 更多