Historically, many developers learn JavaScript after learning languages like C++, Java, C#, Ruby, or Python. All of these languages have a class keyword, and in many of these languages, the class keyword is the primary building block for constructing software.
In modern times, many developers learn JavaScript as a first language, so the new class keyword in ES6 will be a brand new tool.
Regardless of a developer’s background, the class keyword in JavaScript will play a role similar to the class keyword in other languages. Classes allow developers to define a blueprint for constructing objects. Each object a program creates from the class blueprint will be an object with the same methods and placeholders for data specific to each object.
We’ve always had the capability of building object with data and behavior in JavaScript, but like other ES6 features, the class keyword makes the common practice both succinct and more explicit.
Every class has a name, and a body containing the method definitions for the class.
class Employee { hire() { this.hired = true; } getStatus() { if(this.hired) { return "hired"; } } }
The above class has two methods: hire and getStatus. Notice we do not need to use the function keyword to define the methods. These methods will be available on every object we create using Employee, and as you can see in the implementation, these methods can save and retrieve state inside the object using the this keyword.
We create Employee objects using the new keyword.
let developer = new Employee(); developer.hire(); expect(developer.hired).toBe(true); expect(developer.getStatus()).toBe("hired");
Quite often you’ll want an object to initialize itself with specific data right from the start. We can add this initialization logic using a constructor.
Every class may specify a constructor. The runtime will invoke the constructor when instantiating a class, and we can use the constructor to initialize state in an object, often by accepting parameters in the constructor method.
class Employee { constructor(name) { this.name = name; } getName() { return this.name.toUpperCase(); } } let developer = new Employee("Scott"); expect(developer.name).toBe("Scott"); expect(developer.getName()).toBe("SCOTT");
A class can also define a property with get and set to encapsulate a field.
class Employee { constructor(name) { this._name = name; } doWork() { return `${this._name} is working`; } get name() { return this._name.toUpperCase(); } set name(newName){ if(newName){ this._name = newName; } } } let developer = new Employee("Scott"); expect(developer.name).toBe("SCOTT"); developer.name = "Alex"; expect(developer.doWork()).toBe("Alex is working");
ES6 also supports class inheritance and interaction between a class and the class superclass. We’ll take a look at these features in the next installment of the series.