Classes

Course- Javascript >

ECMAScript 6 (codenamed Harmony) is the forthcoming version of the ECMAScript standard that underpins the JavaScript language. This new standard should be ratified sometime in 2015.

ECMAScript 6 is a significant update to the specification, and the first major update to the language since ECMAScript 5 became standardized in 2009. The major browser manufacturers are already working on implementing the new features in their JavaScript engines.

In this secttion we’ll take a look at a few of the most important new features, some of which you can already use.


Classes

In section,"JAVASCRIPT OOPS", you read about OOP and saw examples of how to create and manipulate objects, including this one:

function Car(Color, Year, Make, Miles) {
this.color = Color;
this.year = Year;
this.make = Make;
this.odometerReading = Miles;
this.setOdometer = function(newMiles) {
this.odometerReading = newMiles;
}
}                     
                     

If you’ve come to JavaScript from another programming language you may already be familiar with classes. A class is a representation of an object.

class Car {
constructor(Color, Year, Make, Miles) {
this.color = Color;
this.year = Year;
this.make = Make;
this.odometerReading = Miles;
}
setOdometer(newMiles) {
this.odometerReading = newMiles;
}
}                     
                     

This syntax also allows you to extend classes, creating a new class that inherits the properties of the parent. Here’s an example:

class Sportscar extends Car {
constructor(Color, Year, Make, Miles) {
super(Color, Year, Make, Miles);
this.doors = 2;
}
}                     
                     

Here I’ve used the super keyword in my constructor, allowing me to call the constructor of a parent class and inherit all of its properties. In truth, this is just syntactic sugar; everything using classes can be rewritten in functions and prototypes, just like you learned in section,"JAVASCRIPT OOPS". However, it’s much more compatible with other popular languages, and somewhat easier to read.