They encapsulate data with code to work on that data. Classes are similar to functions. Here, a class keyword is used instead of a function keyword. Unlike functions classes in JavaScript are not hoisted. A JavaScript class is not an object. It is a template for JavaScript objects. Using a Class When you have a class, you can use the class to create objects:
Syntax :
class classname {
constructor(parameter) {
this.classname = parameter;
}
}
Ways to declare
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
// Expression; the class is anonymous but assigned to a variable
const Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
// Expression; the class has its own name
const Rectangle = class Rectangle2 {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
Example 1 :
class emp {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const emp1 = new emp("Geek1", "25 years");
console.log(emp.name)
Example 2 :
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(x) {
return x - this.year;
}
}
let date = new Date();
let year = date.getFullYear();
let myCar = new Car("Ford", 2014);