A quick look at JavaScript class introduced in ECMAScript 6

For those of you who are the fan of Java and C# you certainly know that Java or C# allows us to create a blueprint which we can then use to create a new object based on that blueprint and use all the methods of that super class so we do not need to write the same method again and again in a new Java or C# object.

In javascript we can create a blueprint for an object as well using function and later on initiate a new object based on that blueprint with the the ‘new’ keyword. However, before ECMAScript 6 we can only create a function with javascript and not the real class, but now we can and I am going to show you an example on how to create a class and later on extend that class to create a new object. Alright let gets started.

First of all we create a javascript class which is similar to a class in Java or C# like this.

class Person {

	constructor(job, name) {
		this.job = job;
		this.name = name;
	}
	
	get salary() {
		return this.name + " work as " + this.job + " with the monthly salary of " + this.monthlySalary;
	}
	
	set salary(amount) {
		this.monthlySalary = amount;
	}
}

The class above has a constructor, a get and a set method. Now to extend the class above all we need to do is to create a new object like this.

class John extends Person {
	constructor(job, name) {
		super(job, name);
	}
}

The class above will extend the Person class and calls the parent class’s constructor with the job title and the name of a person.

Finally here is how we use the John class…

var jonny = new John("computer programmer", "jonny"); // the two values will go into the constructor
jonny.salary = 3000; // set the salary with the set method of the Person class
alert(jonny.salary); // call the get method of the person class

Below is the outcome of this simple program.

JavaScript classes introduced in ECMAScript 6
JavaScript classes introduced in ECMAScript 6

ECMAScript 6 is simply so great and now the 7th is coming and I will write more articles on this subject in my blog from time to time.

Like this post? Kindly share!