如何在 es6 中实现实例计数器

How to implement instance counter in es6?

本文关键字:实现 实例 计数器 es6      更新时间:2023-09-26

我正在学习 es6,所以我试图将这些代码从 es5 转换为 es6。

我知道如何在 es5 中制作实例计数器。id建立在A.prototype的基础上,counter建立在A本身之上。当我通过 A 构建实例时,它会触发counter++设置id。因此,它实现了行动inheritance counter

var A = (function () {
    function A() {
        this.id = ++A.counter;
        console.log(this.id);
    }
    A.counter = 0;
    return A;
}());
a = new A();  // 1
b = new A();  // 2
c = new A();  // 3

如果我在 es6 中工作,如何实现相同的功能?

另外两个答案是完全正确的。但是如果你想获得超级疯狂的ES6,你可以为这些属性制作getter。

class A {
    constructor() {
        this._id = A.counter;
        console.log(this.id);
    }
    get id() {
        return this._id;
    }
    static get counter() {
        A._counter = (A._counter || 0) + 1;
        return A._counter;
    }
}
a = new A() // <- 1
b = new A() // <- 2
c = new A() // <- 3

这样,您的计数器和 id 都是只读的,并且每次访问它时您的计数器都会自动递增......此外,它在类定义中都是整洁的,而不需要在类定义之外。

不是说你需要这样做...但看起来你正在学习 ES6,这个例子展示了几个关于你可以用它做什么的巧妙技巧。

你可以用与 ES5 完全相同的方式执行此操作:

class A {
    constructor() {
        this.id = ++A.counter;
        console.log(this.id);
    }
}
A.counter = 0;
var a = new A();  // 1
var b = new A();  // 2
var c = new A();  // 3

(如果需要,您也可以添加相同的不必要的IIFE)

es6 class可以完成您想要的。

id不是建立在A.prototype上,而是在每个A实例上构建的。constructor是做一个实例。所以你可以看看,当类 A 构建一个新实例时,它确实this.id = ++A.counter

class A {
    constructor(){
        this.id = ++A.counter;
        console.log(this.id)
    }
}
A.counter = 0;
a = new A()
b = new A()
c = new A()

这是一个解决方案,它也完全包含在 ES6 类中,作为 BryanGrezeszak 的答案,但具有不同的行为,在某些情况下可能有用:

class A {
  constructor() {
    this.constructor.counter = (this.constructor.counter || 0) + 1;
    this._id = this.constructor.counter;
    console.log(this.id);
  }
  get id() {
    return this._id;
  }
}
class B extends A {}
class C extends A {}
a = new B(); // <- 1
b = new C(); // <- 1
c = new B(); // <- 2
d = new A(); // <- 1

与此代码的区别在于继承的类具有自己的独立计数器。

如果不想向构造函数添加属性,可以替换

this.constructor.counter

Object.getPrototypeOf(this).counter

这是当前表达弃用的方式

this.__proto__.counter

这样counter将是类的静态属性,而不是(静态函数)constructor的属性。