Class is one of the most important concepts in JavaScript. It is a way to create objects that share common properties. Classes are similar to structures in other languages, but they have some important differences.
In this article, we will explore what classes are and how to use them.
What Is A Class In JavaScript?
A class is a template for creating objects. It is a blueprint that defines the variables and the methods common to all objects of a certain kind.
Classes in JavaScript are built on the prototype system. This means that every object has a prototype, and that objects can inherit properties from their prototypes. You can think of a class as a template for creating objects, and the prototype as a template for creating classes.
Object Oriented Programming Prior To ES6 In JavaScript
Classes have been a part of JavaScript for a long time, but they were not originally part of the language. They were added in ES6, which is the sixth edition of the ECMAScript standard.
Before ES6, JavaScript was not a true object-oriented language. Classes were implemented using prototypes, and there was no way to create classes that did not inherit from another class. This made it difficult to create modular code, and it often resulted in code that was difficult to read and understand.
ES6 introduced classes, which provide a more traditional object-oriented programming experience. Classes can be created without inheritance, and they can be used to create modular code. They also make it easier to write code that is easy to read and understand.
Here’s an example of a Player class created prior to ES6 –
var Player = function(){
this.name = ";
this.score = 0;
};
Player.prototype.updateScore = function(){
this.score++;
};
This code does not use classes, but rather, it uses prototypes. The Player variable is created as a function, and the prototype is then attached to that function. This means that every object created using the Player variable will have the updateScore method available to it.
Declaring Classes In ES6
The following code demonstrates how to create a class in ES6 –
class Player{
constructor(name, score){
this.name = name;
this.score = score;
}
updateScore(){
this.score++;
}
}
The class is defined using the class keyword, and it contains a constructor function and an updateScore method. The constructor function takes two parameters – name and score. These parameters are assigned to the members of the class.
When you create a new instance of the class, you can provide values for the name and score members. For example, the following code creates a new instance of the Player class with the name “John” and the score 5 –
var player = new Player("John", 5);
player.updateScore();
This code calls the updateScore method on the player object, which increments the score by 1.
Class names start with a capital letter in JavaScript, and methods are always written in lowercase.
Instance Properties And Methods
Instance properties are members that are specific to a class. They are not shared by the prototype, and they can only be accessed using the instance name.
Instance properties can be used to store data associated with the class, or to store methods that are specific to the class.
Here’s an example of an instance property –
class Employee{
constructor(name, salary){
this.name = name;
this.salary = salary;
}
}
var employee = new Employee("John", 100000);
console.log(employee.name); //John
console.log(employee.salary); //100000
The Employee class has two properties – name and salary. These properties are specific to the instance employee of the Employee class.
You can access these properties using the class instance.
This code will log the values ‘John’ and 100000 to the console, respectively.
Instance methods can also be called using the class instance. Notice that an instance method is defined outside the constructor function.
Here’s an example of an instance method –
class Employee{
constructor(name, salary){
this.name = name;
this.salary = salary;
}
getSalary(){
return this.salary;
}
incrementSalary(){
this.salary++;
}
}
var employee = new Employee("John", 100000);
employee.incrementSalary();
console.log(employee.getSalary());
This code will log the value 100001 to the console. The incrementSalary instance method increments the value of the salary property by 1.
Constructor In JavaScript Classes
A constructor is a method in a class that is run only once during the lifetime of an object – when an object is being created. The constructor method is called by default when an object is created.
A constructor is just like any other method in a class, and you can use it to initialize the instance properties. It is also a good place to put code that creates and initializes the object’s prototype.
Here’s an example of a constructor –
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
}
This code defines a Person class with a constructor that takes two parameters – name and age. The constructor sets the values of the name and age members, and it also sets up the prototype for the class.
You can create a new instance of the Person class by providing values for the name and age members –
var person = new Person("John", 5);
This will call the constructor method with the arguments ‘John’ and 5 respectively.
A constructor need not have any arguments. You can use it to log something to the console, or set some default property values in that case.
class Person{
constructor(){
console.log("This is a person class");
}
}
Defining Classes By Expressions In ES6
You can also define a class by using an expression. Class expressions are of two types – named and unnamed, and the following code demonstrates both types –
let Player = class {
constructor(name, score){
this.name = name;
this.score = score;
}
};
console.log(Player.name); //Player
let Player = class Player2 {
constructor(name, score){
this.name = name;
this.score = score;
}
};
console.log(Player.name); //Player2
this Keyword
The "this" keyword refers to the current object. For example, the following code will log the value of the name member on the current object –
console.log(this.name);
"this" keyword can also be used in methods. The following code demonstrates how to use the this keyword in a method –
class MyClass{
constructor(){
this.name = "John";
}
method(){
console.log(this.name); //John
}
};
var myObj = new MyClass();
myObj.method(); // logs John
The "this" keyword refers to the object that is calling the method. In the example, the myObj object is calling the method, so this will refer to the myObj object.
Hoisting Classes
Classes are hoisted, which means that they are declared before they are used. So, you cannot use the class keyword to create a class after you have used it. For example, the following code will not work –
var player = new Player("John", 5);
class Player{
constructor(name, score){
this.name = name;
this.score = score;
}
}
console.log(player); // This will not work!
The console log statement will not work because the class is used before being declared. To fix this, you can move the class definition to the top of the file.
Classes Versus Structures In Other Languages
Classes are similar to structures in other languages, but they have some important differences. The most important difference is that classes are based on prototypes, while structures are not. This means that classes can inherit properties from their prototypes, while structures cannot.
Another difference is that classes are created using the class keyword, while structures are created using the struct keyword.
Classes also have a few features that structures do not, such as getters and setters. Getters and setters allow you to read and write the values of member variables without having to access them directly.
Here’s an example of a structure created in C++ –
struct Player{
int name;
int score;
};
This code defines a structure called Player. The Player structure contains two member variables – name and score.
Here’s an example of a class created in C++ –
class Player{
public:
int name;
int score;
void updateScore(int newScore){score = newScore;}
};
Getters And Setters In JavaScript Classes
Classes can also have getters and setters. Getters are methods that return the value of a member, and setters are methods that set the value of a member.
The getters and setters behave like methods, but they are just properties of the class.
The following code demonstrates how to create a class with a getter and setter –
class Square {
constructor(_width) {
this.width = _width;
}
get area() {
return this.width * this.width;
}
set area(_area) {
this.width = Math.sqrt(_area);
this.height = this.width;
}
}
let mySquare = new Square(5);
console.log(mySquare.area); //25
mySquare.area = 16;
console.log(mySquare.area); //16
console.log(mySquare.width); //4
console.log(mySquare.height); //4
Notice that you don’t need to call the area method with a parenthesis, because it is just like a property of the Square class.
Inheritance In ES6 Classes
Classes can inherit from other classes, and this allows you to create complex classes by using a combination of simple classes. The following code demonstrates how to create a class that inherits from another class –
class Player{
constructor(name, score){
this.name = name;
this.score = score;
}
getName() {
return this.name;
}
}
class Manager extends Player{
constructor(name, score, team){
super(name, score);
this.team = team;
}
getTeam() {
return this.team;
}
};
The Manager class inherits from the Player class. It overrides the constructor to take two additional parameters – team and manager. The super keyword is used to call the constructor of the parent class.
The Manager class also has a team member, which is assigned to the team parameter.
The following code demonstrates how to create a new manager object and set the team member –
var manager = new Manager("John", 5, "Red Sox");
console.log(manager.getTeam()); //Red Sox
The team member can be accessed using the team property on the manager object.
You cannot access the getTeam method using the person instance, since it is defined in the sub class.
let player = new Player("Kelly", 10);
console.log(player.getTeam()); //player.getTeam is not a function
You can however access the getName method defined in the person class from the manager instance, since the manager class inherits the methods of the person class.
console.log(manager.getName()); //John
Static Methods And Properties
Classes can also have static methods and properties. Static methods are methods that can be called without creating an instance of the class, and static properties are properties that can be accessed without creating an instance of the class.
The following code demonstrates how to create a class with a static method and property –
class StaticClass{
static method() {
console.log("static method");
}
static property="static property";
}
Static methods and properties are accessed using the StaticClass name. The following code demonstrates how to call the static method and access the static property –
StaticClass.method(); //static method
StaticClass.property; //static property
Polymorphism In JavaScript Classes
Polymorphism is a programming principle that allows code to be easily reused by making sure that objects can be treated as if they are of a different type.
In JavaScript, this means that objects can take on multiple forms. For example, a function can be written that can accept either a string or an array as an input. The function would then be able to handle both types of data in the same way. This is said to be “type-safe” because it allows developers to write code without having to worry about the type of data that will be passed into a function.
Polymorphism is a powerful tool that can make code more flexible and easier to read. When used correctly, it can help to prevent errors and make code more maintainable.
Here is an example of polymorphism in JavaScript classes using the standard Animal class example –
class Animal{
constructor(name){
this.name = name;
}
speak(){
console.log("I am a " + this.name + " and I can speak.");
}
}
class Dog extends Animal{
constructor(name, breed){
super(name);
this.breed = breed;
}
speak(){
console.log("Woof Woof");
}
}
The Dog class extends the Animal class, which means that it inherits all of the methods and properties of the Animal class.
The speak method in the Dog class overrides the speak method from the Animal class. This allows you to call the speak method on an instance of the Dog class and it will execute the speak method from the Dog class.
var myDog = new Dog("Max", "German Shephard");
myDog.speak(); //Woof Woof
Since the dog class has a method called speak, the method in the Dog class is called instead of the speak method in the generic Animal class. This is called polymorphism in JavaScript class.
You can call the method of the main class in the overridden method using the super keyword. The following code demonstrates how to do this –
class Animal{
constructor(name){
this.name = name;
}
speak(){
console.log("I am a " + this.name + " and I can speak.");
}
}
class Dog extends Animal{
constructor(name, breed){
super(name);
this.breed = breed;
}
speak(){
console.log("Woof Woof");
console.log("I am a " + this.breed + " and I can speak.");
//Call the speak method from the Animal class using the super keyword.
super.speak();
}
}
var myDog = new Dog("Max", "German Shephard");
myDog.speak();
/*
Woof Woof
I am a German Shephard and I can speak.
I am a Max and I can speak.*/
Classes Vs Functions
There are two ways to define reusable code in JavaScript – classes and functions. Both have their pros and cons, so which one you choose to use depends on your specific needs.
In JavaScript, functions are a way to group together a set of related code. Functions can take input parameters and return an output value. Classes, on the other hand, are a way to create objects. Classes can contain member variables and member functions. Objects are created by instantiating a class.
Classes are hoisted whereas functions are not. This means that you have to declare a class before using it, whereas you can use a method before its declaration.
Classes are more structured than functions. Classes provide a way to define the members of an object, and they also provide a way to create methods that can be used by objects. Functions do not have these features.
Classes are less flexible than functions. Functions can be defined in any order, and you can call them from anywhere in your code. Classes must be defined in a specific order, and they can only be called from within the context of the class.
In general, classes are better suited for creating reusable code, while functions are better suited for small one-time tasks.
When it comes to choosing between a class and a function, there is no right or wrong answer. It depends on the situation and what makes more sense for the particular problem you’re trying to solve.
In general, if you need to group together some functionality that can take input parameters and return an output value, then a function is probably the way to go. If you need to create an object with member variables and member functions, then a class is the better option.
Conclusion
In this blog post, we"ve covered the basics of what classes are in JavaScript and how they work. We looked at some examples of how to create and use classes, as well as some best practices for working with them. We also had a quick look at how inheritance works in JavaScript.
Now that you understand all there is to know about classes in JS, go out and start using them in your own projects!