JavaScript Code

JavaScript Class


Class

class is a blueprint which can be used to create objects of this class type

following is a simple example to create a class Student

class Student {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
  • class is a keyword
  • Student is class name
  • constructor() is method in which we set properties for the class object
  • (name, age) are parameters of the constructor. there can be as many number of constructors as required
  • this.name = name; set the name property of this Student type object with the value received for name parameter in constructor()

Object

to create an object of any class type, use new keyword

following is an example to create a new object of class Student

student1 = new Student('Ram', 12);

Example

create a class named Student, and create 3 objects of class type Student

class Student {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

let student1 = new Student('Ram', 12);
let student2 = new Student('Bob', 9);
let student3 = new Student('Karan', 15);

console.log(student1.name + ', ' + student1.age);
console.log(student2.name + ', ' + student2.age);
console.log(student3.name + ', ' + student3.age);

Class Methods

there can be custom methods inside the class, where the objects can call

following is an example where Student class contains a method printDetails() to print the student details

class Student {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    printDetails() {
        console.log('Name : ' + this.name);
        console.log('Age  : ' + this.age);
        console.log('\n');
    }
}

let student1 = new Student('Ram', 12);
let student2 = new Student('Bob', 9);
let student3 = new Student('Karan', 15);

student1.printDetails();
student2.printDetails();
student3.printDetails();