cha*_*cha 0 javascript class ecmascript-6 es6-class
如果这已经被问到,请告诉我。如何在每个实例上增加类变量?假设我有以下 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)
上面的代码不起作用,我找不到具体的答案,或者某些答案似乎对我不起作用。
您可以使用静态属性来记住已经创建了多少,然后在初始化key实例属性时使用它。static类属性仍然是第 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();Run Code Online (Sandbox Code Playgroud)
但是请注意,任何地方的任何代码都可以分配给以Key.lastKey更改下次将使用的值。
如果要将其设为私有,可以使用私有static类字段。这些也处于第 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();
Run Code Online (Sandbox Code Playgroud)
Stack Snippets 没有插件来处理这个问题,所以这里有一个关于 Babel REPL 的例子。
在该代码中,只有 Key代码才能访问#lastKey.
或者只使用作用域函数:
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();
Run Code Online (Sandbox Code Playgroud)
这仍然依赖于class fields 提案(就像你在你的问题中所做的那样)。如果你想要一个纯ES2015 解决方案,只需删除key声明:
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();Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1264 次 |
| 最近记录: |