Understanding JavaScript Classes and Their Use
JavaScript Classes Introduced with ECMAScript 2015, or ES6, JavaScript Classes provide a way to create templates for JavaScript objects. JavaScript Class Syntax To define a clas...
JavaScript Classes
Introduced with ECMAScript 2015, or ES6, JavaScript Classes provide a way to create templates for JavaScript objects.
JavaScript Class Syntax
To define a class, use the class keyword. It is important to include a method called constructor() in every class:
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
In the example above, a class named "Car" is created with two initial properties: "name" and "year". It's important to note that a JavaScript class is not an object itself but serves as a blueprint for creating objects.
Creating Objects with a Class
Once a class is defined, it can be used to instantiate objects:
let myCar1 = new Car("Ford", 2014);
let myCar2 = new Car("Audi", 2019);
In this example, two objects are created using the Car class, and the constructor method is automatically called to initialize these objects.
The Constructor Method
The constructor method is a special function that:
- Must be named "constructor".
- Executes automatically when a new object instance is created.
- Initializes object properties.
If no constructor is defined, JavaScript provides an empty default constructor.
Class Methods
Methods within a class are defined similarly to other object methods. You can add as many methods as needed to your class. For instance, a method to calculate the age of a car could be added as follows:
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(currentYear) {
return currentYear - this.year;
}
}
Class methods can also accept parameters, allowing for more dynamic behavior.
"use strict"
JavaScript classes need to follow the "use strict" directive rules. Failing to adhere to these rules will result in errors.