SyntaxStudy
Sign Up
JavaScript Class Basics: constructor and Methods
JavaScript Beginner 6 min read

Class Basics: constructor and Methods

Class Basics in JavaScript

ES2015 introduced class syntax as a cleaner, more familiar way to create objects and set up inheritance. Under the hood, JavaScript classes are syntactic sugar over the prototype-based inheritance system, but they provide a much clearer structure for object-oriented code.

The class Keyword

Define a class with the class keyword followed by the class name. Class names conventionally use PascalCase. The class body contains method definitions using the concise method syntax — no commas between methods, unlike object literals.

constructor()

The constructor method is called automatically when you create a new instance with new ClassName(). Use it to initialise instance properties. A class can have at most one constructor.

Instance Methods

Methods defined in the class body are added to the prototype, meaning all instances share a single copy of each method — efficient regardless of how many instances you create.

Example
class Animal {
  constructor(name, sound) {
    this.name = name;
    this.sound = sound;
    this.alive = true;
  }
  speak() {
    return this.name + ' says ' + this.sound;
  }
  describe() {
    return 'I am ' + this.name;
  }
  toString() {
    return 'Animal(' + this.name + ')';
  }
}
const cat = new Animal('Cat', 'meow');
const dog = new Animal('Dog', 'woof');
console.log(cat.speak());    // Cat says meow
console.log(dog.speak());    // Dog says woof
console.log(cat instanceof Animal); // true
console.log(cat.toString()); // Animal(Cat)
console.log(cat.alive);      // true
Pro Tip

Methods are shared on the prototype — do not assign methods in the constructor with this.method = function(){} as that creates a separate copy of the function on every instance, wasting memory.