gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:12:08 25 4
gpt4 key购买 nike

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

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

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

然后我打印 make 几个实例:

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

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

期望的结果是:

1
2
3

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

最佳答案

您可以使用静态属性来记住已经创建了多少个属性,然后在初始化 key 实例属性时使用它。 static class properties仍处于第 3 阶段,因此尚未包含在规范中,但已经相当成熟了。

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();

但请注意,任何地方的任何代码都可以分配给 Key.lastKey 来更改下次使用的值。

如果您想将其设为私有(private),您可以使用 private static class field 。这些也处于第三阶段,但已经相当遥远了:

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();

Stack Snippets 没有插件来处理这个问题,所以 here's an example on the Babel REPL .

在该代码中,只有Key代码可以访问#lastKey

或者只使用作用域函数:

const Key = (() => {
// Only code within this anonymous function has access to `lastKey`
let lastKey = 0;
return class Key {
// 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 = ++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();

这仍然依赖于 class fields proposal (正如您在问题中所做的那样)。如果您想要一个 ES2015 解决方案,只需删除 key 声明即可:

const Key = (() => {
// Only code within this anonymous function has access to `lastKey`
let lastKey = 0;
return class Key {
constructor() {
// Increment and assign
this.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();

关于Javascript - 在每个实例上增加类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59593487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com