Javascript Class Syntax
The class syntax in JavaScript provides developers with a more structured and intuitive way to work with object-oriented programming (OOP) concepts. In this article, we’ll explore the JavaScript class syntax and understand how it simplifies the process of creating and managing objects.
Understanding Object-Oriented Programming (OOP)
Before diving into JavaScript classes, let’s briefly revisit the concept of object-oriented programming. OOP is a programming paradigm that organizes code into reusable objects, which encapsulate both data and the operations that can be performed on that data. These objects are instances of classes, which act as blueprints or templates defining the properties and behavior of the objects.
In traditional JavaScript, OOP was achieved using constructor functions and prototypes. While effective, this approach often led to verbose and error-prone code. The introduction of the class syntax in ES6 aimed to address these challenges by providing a more concise and familiar syntax for working with classes.
Use the keyword class to create a class.
Always add a method named constructor():
class ClassName {
constructor() { … }
}
Example:
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
The example above creates a class named “Bus”.
The class has two initial properties: “name” and “year”.
Using a Class
When you have a class, you can use the class to create objects:
Example:
const myBus1 = new Bus(“Toyota”, 2014);
const myBus2 = new Bus(“Honda”, 2019);
The example above uses the Bus class to create two Bus objects.
The Constructor Method
The constructor method is a special method:
- It has to have the exact name “constructor”
- It is executed automatically when a new object is created
- It is used to initialize object properties
If you do not define a constructor method, JavaScript will add an empty constructor method.
Class Methods
Class methods are created with the same syntax as object methods.
Use the keyword class to create a class.
Always add a constructor() method.
Then add any number of methods.
Syntax
class ClassName {
constructor() { … }
method_1() { … }
method_2() { … }
method_3() { … }
}
Create a Class method named “age”, that returns the Bus age:
class Bus {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
const date = new Date();
return date.getFullYear() – this.year;
}
}
const myBus = new Bus(“Toyota”, 2014);
document.getElementById(“demo”).innerHTML =
“My bus is ” + myBus.age() + ” years old.”;
You can send parameters to Class methods:
Example
class Bus {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(x) {
return x – this.year;
}
}
const date = new Date();
let year = date.getFullYear();
const myBus = new Bus(“Toyota”, 2014);
document.getElementById(“demo”).innerHTML=”My Bus is ” + myBus.age(year) + ” years old.”;