我在學習es6,所以我試圖將這些代碼從es5轉換爲es6。如何在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工作,我該如何實現相同的功能?
'id'不是建立在'A.prototype'上,而是建立在每個A實例上。 – Bergi
https://babeljs.io/repl/#?evaluate=true&presets=es2015%2Creact%2Cstage-2&experimental=true&loose=false&spec=true&playground=true&code=class%20A%20%7B%0A%20%20constructor()%20 %7B%0A%20%20%20%20this.id%20%3D%20%2B%2BA.counter%3B%0A%20%20%7D%0A%7D%0A%0AA.counter%20%3D %200%3B%0A%0Aconst%20A%20%3D%20new%20A()%3B%0Aconst%20B%20%3D%20new%20A()%3B%0A%0Aconsole.log(a.id%2C %20b.id) – zerkms