Facebook Pixel

Constructor Functions vs ES6 Classes in JavaScript

Both use prototypes. Here is how they compare.

Constructor Functions vs ES6 Classes

Constructor Function

function Person(name) { this.name = name; } Person.prototype.greet = function () { return `Hello, ${this.name}`; }; function Student(name, grade) { Person.call(this, name); this.grade = grade; } Student.prototype = Object.create(Person.prototype); Student.prototype.constructor = Student;

ES6 Class

class Person { constructor(name) { this.name = name; } greet() { return `Hello, ${this.name}`; } } class Student extends Person { constructor(name, grade) { super(name); this.grade = grade; } }

Key Differences

  • Syntax: classes are cleaner and more readable.
  • Inheritance: extends and super vs manual Object.create and Person.call.
  • new requirement: classes throw without new; constructors don't.
  • Hoisting: classes are not hoisted; constructors are (function declarations).
  • Strict mode: classes are always strict; constructors are not by default.

Under the Hood

ES6 classes are syntactic sugar over the prototype system. class Person { greet() {} } puts greet on Person.prototype. extends sets up the prototype chain. It is the same mechanism.

The Takeaway

ES6 classes are syntactic sugar over constructor functions and prototypes. Classes are cleaner, enforce new, and are always strict. Constructor functions are the old way with manual prototype chain setup. Use classes in modern code.

Classes have cleaner syntax, use extends/super for inheritance, throw without new, are not hoisted, and are always strict. Constructor functions require manual prototype chain setup and do not enforce new. Classes are syntactic sugar over the same prototype system.

Yes. class Person { greet() {} } puts greet on Person.prototype. extends sets up the prototype chain (Student.prototype.__proto__ = Person.prototype). Under the hood, it is the same prototypal inheritance.

Yes. Calling a class constructor without new throws TypeError: Class constructor Person cannot be invoked without 'new'. This prevents the forgotten-new bug that constructor functions have.

Student.prototype = Object.create(Person.prototype); Student.prototype.constructor = Student;. In the constructor: Person.call(this, name). This sets up the prototype chain manually. ES6 extends does this automatically.

No. Classes are not hoisted (unlike function declarations). You must declare a class before using it. This is intentional: classes use TDZ (temporal dead zone) like let/const.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.