Open In App

Differences between ES6 class and ES5 function constructors

Last Updated : 17 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss the difference between the ES6 class and ES5 function constructors. Both serve the purpose of creating new objects, still, they have some differences between them.

ES6 Class constructors: ES6 class constructors work quite the same as class constructors in other object-oriented languages. They are used to create new objects.

Javascript




class User {
    constructor(name, age, gender) {
        this.name = name;
        this.age = age;
    this.gender = gender;
    }
    print() {
        console.log(`${this.name} has an age of 
        ${this.age} and gender of ${this.gender}`);
    }
}
  
const Roy = new User('Roy', '19', 'Male');
Roy.print();


Output:

"Roy has an age of 19 and gender of Male"

ES5 function constructor: ES5 function constructors are also used to create objects. The above example can be modified as following through the use of function constructors.

Javascript




function User(name, age, gender) {
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.print = function () {
        console.log(`${this.name} has an age of ${this.age} 
                        and gender of ${this.gender}`);
    };
}
  
const Roy = new User('Roy', '19', 'Male');
Roy.print();


Output:

"Roy has an age of 19 and gender of Male"

Difference between ES6 class and ES5 function  constructors:

                          ES6 class constructors                          ES5 function constructors
As discussed above ES6 class constructors creates objects by adding function to their prototypes (Blueprint). ES5 function constructors also create objects along with inheritance property. 
It ensures that this keyword used by the developer is referring to the object being created by the developer.  Any function can be used as a function constructor and it primarily focuses on the creation of reusable object creation code.
Its syntax is similar to object creation in other object-oriented programming languages. Its syntax is unique and is not generally found in other object-oriented programming languages.
This can be said to be a syntax base for constructor functions and instantiate objects using a new operator. This also uses a new operator for object creation but focuses on how the objects are being instantiated.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads