How to Rebuild a Counter with ES6 Classes
Okay! Let’s rebuild the counter I made three years ago, this time using ES6 Classes. You can check the CodePen link below.
How to Rebuild a Counter with ES6 class
Okay! Let’s rebuild the counter I made three years ago, this time using ES6 Classes. You can check the CodePen link below.
[embed]
Before we dive in, there are a few concepts you need to know first:
1. Class
With ES6 class, you don't need to manually extend functions using prototype. It makes the code way easier to read.
function Car(color, speed) {
this.color = color;
this.speed = speed;
}
Car.prototype.drive = function () {
console.log(`The ${this.color} car is driving at ${this.speed} km/h.`);
};
//the difference between using class feature or not
class Car {
constructor(color, speed) {
this.color = color;
this.speed = speed;
}
drive() {
console.log(`The ${this.color} car is driving at ${this.speed} km/h.`);
}
}
const myCar = new Car('red', 120);
myCar.drive();
2. class + constructor()
In ES5, functions are scattered, and if you want to build a new object, you have to manually set up functions and prototypes each time. But with ES6 class and constructor, you can easily create new objects just by using new, keeping everything organized in one place.
class Car {
constructor(color, speed) { ... }
drive() { ... }
}
const car1 = new Car('red', 120);
const car2 = new Car('blue', 80);
3. Arrow Function
Automatic this binding and no need to write return for simple expressions.
// tarditional function
function add(a, b) {
return a + b;
}
// arrow function
const add = (a, b) => a + b;
Now, let’s upgrade the old counter :)
First, turn the global variable into a class
class Timer {
constructor() {
this.time = 0;
this.interval = null;
}
}
and move all the function into the class
class Timer {
constructor() {
this.time = 0;
this.interval = null;
}
updateTime() {
console.log(this.time);
}
startCount() {
console.log('Start counting...');
}
reset() {
console.log('Reset timer');
}
}
Second, bind the time variable to this, so it belongs to the class instance.
this.time += 1;
this.updateTime();
Third, Update setInterval() to use an arrow function. Because in function() {}, this refers to the global object (like window),
so it causes an error — there's no window.time.
start() {
setInterval(() => {
console.log(this.time);
}, 1000);
}
Here is the final result!
[embed]
Hope this gives you a clearer idea of how to refactor simple functions into ES6 Classes!
메타데이터
- post_id
- 654a52b6abce
- slug
- how-to-rebuild-a-counter-with-es6-classes-654a52b6abce
- url
- https://medium.com/@penny-chang/how-to-rebuild-a-counter-with-es6-classes-654a52b6abce
- canonical_url
- https://medium.com/@penny-chang/how-to-rebuild-a-counter-with-es6-classes-654a52b6abce
- author_url
- https://medium.com/@penny-chang
- status
- ok
- fetched_at
- 2026-07-28 05:39:03