📜  4. 每次使用 JS 中的 new 实例化对象时,您都想打印增量计数 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:33.930000             🧑  作者: Mango

代码示例1
class Key {
    // The static property
    static lastKey = 0;
    
    // The instance property using the class fields proposal syntax
    // Note I didn't initialize it with 1, that's a bit misleading.
    key;
    
    constructor() {
        // Increment and assign
        this.key = ++Key.lastKey;
    }

    print_key() {
        console.log(this.key)
    }
}

const key1 = new Key();
const key2 = new Key();
const key3 = new Key();

key1.print_key();
key2.print_key();
key3.print_key();