In object-oriented programming, classes is a great feature, it also help in creating many objects of same kind. Syntax:
class MyClass { // class methods constructor() { ... } method1() { ... } method2() { ... } ... }
Example 1: Create class
class Student { constructor(name) { this.name = name; } welcome() { console.log(this.name); } } let student = new Student("Ankit"); //object called, constructor created student.welcome(); new Student("Ankit").welcome(); //can be called without variable
Using new keyword, object is created and its constructor called automatically. In JavaScript, a class is a kind of function.
console.log(typeof Student); // function
Just like functions, classes can be defined inside another expression,
Example 2: Class Expression
let student = class Student { welcome() { console.log('Welcome Student'); } } new student().welcome();
Just like literal objects, classes may include getters/setters to compute properties.
class Student { constructor(name) { this.name = name; //invokes the setter } get name(){ return this._name; } set name(value){ this._name = value; } } let student = new Student("Ankit"); //object called, constructor created console.log(student.name); //invokes the getter
Ad: