JavaScript by Example

Classes and `this`

The class syntax, constructors, instance properties, and methods shared through JavaScript's prototype system.

class is syntax over JavaScript's prototype system. Each instance gets its own properties, while methods are shared through the prototype.

A class groups related state and behavior. The constructor runs when you call new and sets up instance properties. Methods are defined in the class body and are available on every instance through the shared prototype.

class Counter {
  constructor(start = 0) {
    this.count = start;
  }
 
  increment() {
    this.count += 1;
  }
 
  decrement() {
    this.count -= 1;
  }
 
  value() {
    return this.count;
  }
}
 
const c = new Counter();
c.increment();
c.increment();
c.increment();
c.decrement();
console.log(c.value()); // 2
 
const c2 = new Counter(10);
c2.increment();
console.log(c2.value()); // 11

In production

Use classes when state and behavior naturally belong together. If the object only stores data, a plain object is simpler.

Enjoyed this? Get more software craft delivered to your inbox.