🥳
Black Friday Sale is on: Get Amazing deals on tools and resourcess
postImage

Tutorial: Javascript Classes

blogImage

By Emmanuel Chinonso

Web Developer

JavaScript Classes

JavaScript Classes were introduced in ECMAScript 2015, often known as ES6. JavaScript Classes are JavaScript Object templates.

Contrast Bootstrap UI Kit

JavaScript Class Syntax

Use the class keyword to create a new class. Always include a constructor() method:

Syntax

1class ClassName {
2 constructor() { ... }
3}

JavaScript Code:

1class Car {
2 constructor(name, year) {
3 this.name = name;
4 this.year = year;
5 }
6}

The code above generates a "Car" class. "Name" and "Year" are the two initial properties of the class. A JavaScript class isn't the same thing as an object. It is a JavaScript object template.

Using a Class: When you have a class, you may utilize it to make objects like these:

JavaScript Code:

1let myCar1 = new Car('Ford', 2014);
2let myCar2 = new Car('Audi', 2019);

The Car class is used to construct two Car objects in the code above. When a new object is formed, the constructor method is automatically invoked.

The Constructor Method

The constructor method is unique:

  • It must be named exactly "constructor"
  • It is called automatically when a new object is created
  • It is used to set up object properties

If you don't declare a constructor method, JavaScript creates one for you.

Class Methods

The same syntax applies to class methods as it does to object methods. To make a class, use the keyword class. A constructor() method should always be included. Then add as many methods as you want.

Syntax

1class ClassName {
2 constructor() { ... }
3 method_1() { ... }
4 method_2() { ... }
5 method_3() { ... }
6}

Make a class method called "age" that returns the age of the car:

JavaScript Code:

1class Car {
2 constructor(name, year) {
3 this.name = name;
4 this.year = year;
5 }
6 age() {
7 let date = new Date();
8 return date.getFullYear() - this.year;
9 }
10}
11let myCar = new Car('Ford', 2014);
12document.getElementById('demo').innerHTML = 'My car is ' + myCar.age() + ' years old.';

You can send parameters to Class methods:

JavaScript Code:

1class Car {
2 constructor(name, year) {
3 this.name = name;
4 this.year = year;
5 }
6 age(x) {
7 return x - this.year;
8 }
9}
10let date = new Date();
11let year = date.getFullYear();
12let myCar = new Car('Ford', 2014);
13document.getElementById('demo').innerHTML = 'My car is ' + myCar.age(year) + ' years old.';

Class Inheritance

Use the extends keyword to construct a class inheritance. When a class is formed using class inheritance, it inherits all of the methods from the parent class: Create a "Model" class that inherits the methods from the "Car" class:

JavaScript Code:

1class Car {
2 constructor(brand) {
3 this.carname = brand;
4 }
5 present() {
6 return 'I have a ' + this.carname;
7 }
8}
9class Model extends Car {
10 constructor(brand, mod) {
11 super(brand);
12 this.model = mod;
13 }
14 show() {
15 return this.present() + ', it is a ' + this.model;
16 }
17}
18let myCar = new Model('Ford', 'Mustang');
19document.getElementById('demo').innerHTML = myCar.show();

The parent class is referred to by the super() function. We invoke the parent's constructor method and gain access to the parent's properties and methods by calling the super() function in the constructor method. Inheritance is important for code reuse since it allows you to reuse attributes and functions from another class when creating a new one.

Getters and Setters You can also use getters and setters with classes. Using getters and setters for your properties might be beneficial, especially if you want to do anything unique with the value before returning it or setting it. Use the get and set keywords to add getters and setters to the class. For the "carname" property, make a getter and a setter

JavaScript Code:

1class Car {
2 constructor(brand) {
3 this.carname = brand;
4 }
5 get cnam() {
6 return this.carname;
7 }
8 set cnam(x) {
9 this.carname = x;
10 }
11}
12let myCar = new Car('Ford');
13document.getElementById('demo').innerHTML = myCar.cnam;

When you want to get the property value from a getter that is a method, you don't use parentheses. The getter/setter method's name cannot be the same as the property's name, in this example carname. To distinguish the getter/setter from the actual property, many programmers use the underscore character before the property name: To distinguish the getter/setter from the actual property, use the underscore character:

JavaScript Code:

1class Car {
2 constructor(brand) {
3 this._carname = brand;
4 }
5 get carname() {
6 return this._carname;
7 }
8 set carname(x) {
9 this._carname = x;
10 }
11}
12let myCar = new Car('Ford');
13document.getElementById('demo').innerHTML = myCar.carname;

Use the same syntax as when setting a property value, but without the parentheses:Use a setter to change the carname to "Volvo":

JavaScript Code:

1class Car {
2 constructor(brand) {
3 this._carname = brand;
4 }
5 get carname() {
6 return this._carname;
7 }
8 set carname(x) {
9 this._carname = x;
10 }
11}
12
13let myCar = new Car('Ford');
14myCar.carname = 'Volvo';
15document.getElementById('demo').innerHTML = myCar.carname;

Hoisting Class declarations, unlike functions and other JavaScript declarations, are not hoisted. That is, before you can use a class, you must first declare it:

JavaScript Code:

1//You cannot use the class yet.
2//myCar = new Car("Ford")
3//This would raise an error.
4class Car {
5 constructor(brand) {
6 this.carname = brand;
7 }
8}
9//Now you can use the class:
10let myCar = new Car('Ford');

When you try to use additional declarations, such as functions, before they are declared, you will not get an error because the default behavior of JavaScript declarations is hoisting (moving the declaration to the top). The class's static methods are declared on the class's level. A static method can only be called on an object class, not on an individual object.

JavaScript Code:

1class Car {
2 constructor(name) {
3 this.name = name;
4 }
5 static hello() {
6 return 'Hello!!';
7 }
8}
9let myCar = new Car('Ford');
10// You can calll 'hello()' on the Car Class:
11document.getElementById('demo').innerHTML = Car.hello();
12
13// But NOT on a Car Object:
14// document.getElementById("demo").innerHTML = myCar.hello();
15// this will raise an error.

You can pass the myCar object as an argument to the static method if you want to use it:

JavaScript Code:

1class Car {
2 constructor(name) {
3 this.name = name;
4 }
5 static hello(x) {
6 return 'Hello ' + x.name;
7 }
8}
9let myCar = new Car('Ford');
10document.getElementById('demo').innerHTML = Car.hello(myCar);

Contrast Bootstrap UI Kit

Create Stunning websites and web apps

Trying to build out all user interfaces and components for your website or web app from scratch can become a very tedious task. A huge reason why we created Contrast Bootstrap to help reduce the amount of time we spend doing that, so we can focus on building some other aspects of the project. Contrast Bootstrap PRO consists of a UI Kit featuring over 10000+ component variants. Together with a template of 5 admin dashboards and 23+ additional multipurpose pages template for building almost any type of website or web app. You can view a demo and learn more about Contrast by clicking here.Try contrast pro

ad-banner

Contrast Bootstrap PRO was built using the most popular CSS framework Bootstrap to help build your next landing, admin SAAS, prelaunch etc project with a clean, prebuilt and well documented template and UI components.Learn more about Contrast

Related Posts

Comments

...