You can use a static property to remember how many have already been created, then use that when initializing your key instance property. static class properties are still Stage 3 so they aren't in the spec yet, but they're fairly far along.
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();
Note, though, that any code anywhere can assign to Key.lastKey to change what value it will use next time.
If you want to make it private, you can use a private static class field. Those are also at Stage 3 but fairly far along:
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 don't have the plugin to handle that, so here's an example on the Babel REPL.
In that code, only Key code can access #lastKey.
Or just use a scoping function:
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();
That still relies on the class fields proposal (as you did in your question). If you want a pure ES2015 solution, just remove the key declaration:
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();