JavaScript Constructors vs. Classes – DEV Community


JavaScript introduced classes, similar to other languages. Classes enable us to avoid writing the same code for different objects. They work as templates, making the code easier to read and more understandable. Before going in-depth into classes, I’ll talk about the difference between constructor functions and classes in this blog.

Constructor or Constructor Function
A constructor function is a regular JavaScript function used to create and initialize objects. It allows you to create multiple objects with the same structure (properties and methods) without repeating code.

  1. By convention, constructor functions start with a capital letter (e.g., User) to distinguish them from regular functions.
  2. Constructor functions should be executed with the new operator.
function User (name) {
    this.name = name;
    this.admin = false;
}

let john = new User("John");
console.log(john.name); // John
console.log(john.admin); // false
Enter fullscreen mode

Exit fullscreen mode

When the new operator is called, the following steps occur:

  1. A new empty object is created and assigned to this.
  2. The constructor function’s body is executed, and usually this is modified by assigning properties or methods to it.
  3. The this object is returned implicitly unless another object is explicitly returned.
function User(name) {   
    // this = {};  (implicitly) 

    // add properties to this 
    this.name = name; 
    this.isAdmin = false;   

    // return this;  (implicitly) 
}
Enter fullscreen mode

Exit fullscreen mode

When a new object is created, something like this happens:

let user = new User("John");

this = {};
this = {
    name: "John",
    isAdmin: false
}
return this;
Enter fullscreen mode

Exit fullscreen mode

Classes
Classes were introduced in ES6 as a more modern and structured way to define objects and their behavior.

Syntax

class MyClass { 
    // class methods 
    constructor() { ... } 
    method1() { ... } 
    method2() { ... } 
    method3() { ... } 
    ... 
}
Enter fullscreen mode

Exit fullscreen mode

Example:

class User { 
    constructor(name) { 
        this.name = name; 
    } 
    sayHi() { 
        alert(this.name); 
    } 
} 
// Usage: 
let user = new User("John"); 
user.sayHi();
Enter fullscreen mode

Exit fullscreen mode

MDN

Classes are functions. Every function has the prototype property. So, when we create a class User {...}, it points to User.prototype and stores methods.

So, essentially, constructor functions and classes do the same things under the hood. However, the newly introduced class syntax adds features such as:

  • Strict mode by default
  • Native support for extends and super
  • static methods
  • Native support for get and set
  • Non-enumerable methods

In the upcoming blogs, I’ll continue exploring classes in JavaScript.



Source link