Difference between Class and Prototype inheritance?
JavaScript classes are syntax built on top of prototypes, so both use the same prototype-based inheritance underneath; classes add clearer syntax plus stricter rules and features that hand-written prototypes lack.
Prototype style (pre-2015)
You write a constructor function, attach methods to Fn.prototype, call the parent constructor with Parent.call(this, ...), and link prototypes with Object.create(Parent.prototype), remembering to restore constructor. It works but is verbose and easy to get wrong.
Class style
class Child extends Parent with constructor, super(...), methods, getters and static members in one block. It produces almost the same prototype structure.
What classes add on top
- Must be called with
new; calling a class as a function throws. - Always strict mode inside the body.
- Not hoisted for use: classes are in the TDZ until their declaration runs.
superfor calling parent constructors and methods.- Private fields and methods (
#secret), truly inaccessible from outside. - Static blocks and public class fields.
- Methods are non-enumerable, so they do not appear in
for...in. - Inheriting from built-ins like
Array,ErrorandMapworks correctly.
Is JavaScript "classical" now?
No. Under the hood objects still link to other objects. You can still change prototypes at runtime and mix in behaviour, which classical languages do not allow.
Recommendation
Use class for new code; understand prototypes so you can read older code and debug inheritance.
Code example
1// Prototype style2function AnimalFn(name) {3 this.name = name;4}5AnimalFn.prototype.speak = function () {6 return `${this.name} makes a sound`;7};8function DogFn(name) {9 AnimalFn.call(this, name); // call parent constructor10}11DogFn.prototype = Object.create(AnimalFn.prototype); // link prototypes12DogFn.prototype.constructor = DogFn; // restore constructor13DogFn.prototype.speak = function () {14 return `${AnimalFn.prototype.speak.call(this)}: woof`;15};1617// Class style: same structure, less ceremony, more features18class Animal {19 #secret = "hidden"; // truly private20 constructor(name) {21 this.name = name;22 }23 speak() {24 return `${this.name} makes a sound`;25 }26}27class Dog extends Animal {28 speak() {29 return `${super.speak()}: woof`;30 }31}3233console.log(new DogFn("Rex").speak()); // Rex makes a sound: woof34console.log(new Dog("Rex").speak()); // Rex makes a sound: woof35console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true - prototypes underneath3637try {38 Dog("oops"); // classes must be called with new39} catch (e) {40 console.log(e.name); // TypeError41}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.