What are the contrasts between ES6 class and ES5 function constructors?

844    Asked by VirginiaMathis in Python , Asked on Jan 11, 2020
Answered by Arun Singh

Allows first take a gander at case of each:

//ES5 Function Constructor

function Person(name) {

this.name = name;

}

//ES6 Class

class Person {

constructor(name) {

this.name = name;

}

}

For straightforward constructors, they look really comparative.

The primary contrast in the constructor comes when utilizing inheritance. On the off chance that we need to make a Student class that subclasses Person and include a studentId field, this is the thing that we need to do notwithstanding the abovementioned.

//ES5 Function Constructor

function Student(name, studentId) {

//Call constructor of the superclass to introduce superclass-inferred members.

Person.call(this, name);

//Initialize subclass' own members.

this.studentId = studentId;

}

Student.prototype = Object.create(Person.prototype);

Student.prototype.constructor = Student;

//ES6 Class

class Student extends Person {

constructor(name, studentId) {

super(name);

this.studentId = studentId;

}

}

It's considerably more verbose to utilize legacy in ES5 and the ES6 adaptation is more clear and remember.



Your Answer

Interviews

Parent Categories