Javascript-每个实例上的增量类变量

问题描述 投票:0回答:1

让我知道是否已经被询问过。如何在每个实例上增加类变量?假设我有以下Key类,我想在创建实例时增加key变量,我尝试过:

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

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

然后我打印一些实例:

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

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

期望的结果将是:

1
2
3

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

javascript class ecmascript-6 es6-class
1个回答
1
投票

您可以使用静态属性来记住已经创建了多少,然后在初始化key实例属性时使用它:

class Key {
    // The static property
    static lastKey = 0;
    
    // The instance property using the class fields proposal syntax
    key = 1
    
    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();

-2
投票

您可以通过这种方式来完成,我已经添加了add_key()实例,通过这种方式,您可以在需要的时候调用add_key()多次,然后通过print_key()进行重新打印

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

  add_key() {
    this.key = this.key + 1
  }
  
  print_key() {
    console.log(this.key)
  }
}

key = new Key()

key.add_key()
key.print_key()
© www.soinside.com 2019 - 2024. All rights reserved.