ES2015 Classes
Vinicius Negrisolo JavaScript >
ES2015 has classes in its specification. So let’s see how we could apply the new ES2015 class syntax for wrapping out our JavaScript code.
ES2015
ES2015, short for ECMAScript 2015, is a new javascript version and it has this name because it was ratified in June 2015. New features and new syntax was incorporated over the current javascript ES5. Because of that ES2015 is also know as ES6. Truth to be told this is a major upgrade to the language since ES5 was defined in 2009.
Some of the new features and syntax proposed by ES2015 is already implemented in modern browsers like Chrome. Otherwise, there’s always an option to transpile your code to supported versions. A well known tool to transform new ES2015 syntax to current/old ES5 is Babel, but there’s also a lot of tools for that purpose.
ES2015 creates the concept of class, and that’s just a syntax sugar for the old prototype based pattern.
ES5 function Constructor
So let’s glance how we build class stylish objects in ES5, starting with the pair function
and new
:
function Car(color) {
this.color = color;
this.park = function() {
console.log('Parking ' + this.color + ' car.');
};
}
var car = new Car('red');
car.park();
//=> Parking red car.
car.color;
//=> "red"
ES5 javascript object
Similarly you can build a class stylish with javascript objects, such as:
Car = {
color: null,
park: function() {
console.log('Parking ' + this.color + ' car.');
}
}
car = Object.create(Car);
car.color = 'red';
car.park();
//=> Parking red car.
car.color;
//=> "red"
ES2015 class
Finally ES2015 brought us the class
syntax with the features extend
and static
.
class Vehicle {
constructor(driver) {
this.driver = driver;
}
static consumerReport(distance, fuel) {
console.log("It's consuming " + (distance/fuel));
}
}
class Car extends Vehicle {
constructor(driver, color) {
super(driver);
this.color = color;
}
park(){
console.log(this.driver + ' is parking the ' + this.color + ' car.');
}
}
Vehicle.consumerReport(150, 12);
//=> It's consuming 12.5
var car = new Car('Bob', 'red');
car.park();
//=> Bob is parking the red car.
car.color;
//=> "red"
Conclusion
New ES2015 syntax bring us a lot of improvements into the language. The new class syntax can help JavaScript code to be more reusable and maintainable. Additionally there’s tools that support us to use the new syntax, even if they are not fully implemented in all browsers. So it’s time to use ES2015.