JavaScript Classes are a template for creating objects. A class encapsulates data and functions (methods) that manipulate data. Use the keyword class
to create a class.
class ClassName {
constructor() { ... }
}
The constructor method is a special method for creating and initializing an object created with a class
. There can only be one special method with the name “constructor” in a class.
Use the super
keyword to call the constructor of the superclass.
JavaScript Classes
A simple example creates a class named “Car” with two initial properties: “name” and “year”. Use the class by creating objects:
<!DOCTYPE html>
<html>
<body>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
let myCar1 = new Car("Tesla", 2008);
let myCar2 = new Car("BMW", 1916);
console.log(myCar1)
console.log(myCar2)
</script>
</body>
</html>
Output:
You can add any number of methods in the class.
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
let date = new Date();
return date.getFullYear() - this.year;
}
}
let myCar1 = new Car("Tesla", 2008);
let myCar2 = new Car("BMW", 1916);
console.log(myCar1.age())
console.log(myCar2.age())
Output: 14
106
It is easy to define methods in the JavaScript class. You simply give the name of the method followed by ()
. For example,
class Person {
constructor(name) {
this.name = name;
}
// defining method
greet() {
console.log(`Hello ${this.name}`);
}
}
let person1 = new Person('John');
// accessing property
console.log(person1.name); // John
// accessing method
person1.greet(); // Hello John
Do comment if you have any doubts or suggestions on this JS basics topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version