Member-only story
JavaScript uniquely blends classical inheritance familiar to Java and C++ along with prototypal inheritance differently from most languages. This flexibility allows multiple inheritance approaches, but when should you use classes versus pure prototypal coding?
In this article we’ll compare JavaScript classes and prototype-based techniques — their syntax, models, and use cases to help determine what fits your coding needs.
Class Syntax
ES6 introduced JavaScript classes mirroring class-based syntax from object-oriented languages:
class Dog {
constructor(breed) {
this.breed = breed;
}
bark() {
console.log(`Woof, I am a ${this.breed} dog!`);
}
}
const myDog = new Dog("Labrador");
myDog.bark();
This syntax defines a Dog class with a constructor and methods. We instantiate a myDog object and call bark(). Familiar to Java, C#, and C++ developers.
Behind the scenes, classes still use prototypes and constructors functions. But this declarative syntax models class-based inheritance avoiding the need to manually tune prototypes.
Prototype Syntax
JavaScript’s original prototypal inheritance works differently than traditional classes: