Classes

class Test{
 doWork(){
  return "Class Test";
 }
 testMethod(){
  return "Method";
 }
}
 let t = new Test();  
 
 e.doWork();     //returns "Class Test"
 e.testMethod(); //returns "Method"

constructor

class Employee{

 constructor(name){
  this._name = name;
 }
 getName(){
  return this._name;
 }
}
 
let e1 = new Test("John");  
let e1 = new Test("Jane");  

 
e1.getName();     //returns "John"
e2.getName();     //returns "Jane"

getters and setters

class Employee{

 constructor(name){
  this.name = name;
 }
 get name(){
  return this._name;
 }
 
 set name(value){
  this._name = value;
 }
}
 
let e1 = new Test("John");  
let e1 = new Test("Jane");  

 
e1.name;     //returns "John"
e2.name;     //returns "Jane"

e2.name = "Alex";
e2.name;    //returns "Alex"

Inheritance

used when there "is-a" relationship.

class Person{ contrustor(name){ this.name = name; } get name(){ return this._name; } set name(){ if(value) this._name = value; } } }

class Employee extends Person{
    doWork(){
        return `${this._name} is working`;
    }
}

let p1 = new Person ("John");
let e1 = new Employee ("Jane");

p1.name;        //returns "John"
e1.name;        //returns "Jane" 
e1.doWork()    ///returns "Jane is Working"

super keyword

super key is used to call/invoke the parent's constructor.

class Person{ contrustor(name){ this.name = name; } get name(){ return this._name; } set name(){ if(value) this._name = value; } } }

class Employee extends Person{
    constructor(title, name){
        super(name);
        this._title = title;
    }
    
    get title(){
        return this._title;
    }
    doWork(){
        //super(); //it can be used in other methods also
        return `${this._name} is working`;
    }
}

let e1 = new Employee ("Developer", "John");

e1.name;        //returns "John" 
e1.title;     //returns "Developer"
e1.doWork()    ///returns "John is Working"

override methods

  • super keyword

class Person{

 constructor(name){
  this.name = name;
 }
 get name(){
  return this._name;
 }
 
 set name(value){
  if (value)
   this._name = value;
 }
 
 doWork(){
  return "free";
 }
}
class Employee extends Person{
    constructor(title, name){
        super(name);
        this._title = title;
    }
    
    get title(){
        return this._title;
    }
    doWork(){
        return super() + "paid" //can also invoke doWork method of the parent class.
            //if this keyword is used it will invoke the method of the same class i.e Employee and it will give StackOverflow error.
    }
}

let e1 = new Employee ("Developer", "John");
let p1 =  new Person ("Alex");

p1.doWork()
e1.doWork()
  • toString

Last updated