小编cha*_*cha的帖子

Javascript - 在每个实例上增加类变量

如果这已经被问到,请告诉我。如何在每个实例上增加类变量?假设我有以下 Key 类,我想在创建实例时增加 key 变量,我尝试过:

class Key{
    key = 1
    constructor(){
        this.key = key
        Key.key++
    }

    print_key(){
        console.log(this.key)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我打印 make 几个实例:

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

key1.print_key()
key2.print_key()
key3.print_key()
Run Code Online (Sandbox Code Playgroud)

想要的结果是:

1
2
3
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用,我找不到具体的答案,或者某些答案似乎对我不起作用。

javascript class ecmascript-6 es6-class

0
推荐指数
1
解决办法
1264
查看次数

标签 统计

class ×1

ecmascript-6 ×1

es6-class ×1

javascript ×1