JavaScript Classes
JavaScript Classes were introduced in ECMAScript 2015, also known as ES6
JavaScript Classes are like blueprints for JavaScript Objects.
JavaScript Class Syntax
Apply the term class
to generate a class.
Make sure to include a function called constructor()
at all times
Syntax
class ClassName {
constructor() { ... }
}
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
The provided code establishes a class called "Car."
The class initially has two properties: "name" and "year."
A JavaScript class is different from an object.
This is a model for JavaScript objects, using the template concept..
Using a Class
When you have a class, you can use it to make things called objects:
The illustration above employs the Car class to generate two Car objects.
The constructor method gets triggered automatically when a fresh object is made.
The Constructor Method
The constructor method is a unique function:
- Ensure that the name "constructor" is precisely used.
- The process happens on its own when a new item is made.
- It is employed to set up the characteristics of an object.
If you don't create a constructor method, JavaScript will automatically include an empty one for you.
Class Methods
Class methods are made using the same structure as methods for objects.
Utilize the word "class" within the class
tag to form a class.
Make sure to include a constructor()
method at all times.
Next, include as many methods as you need.
Syntax
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
Build a class method called "age" that gives the age of the car.
You can pass information to methods in a class
"use strict"
The coding style in classes should be in "strict mode."
If you don't adhere to the rules of "strict mode," you'll encounter an error.