javascript es6 classes code example

Example 1: es6 class example

<script>
   class Student {
      constructor(rno,fname,lname){
         this.rno = rno
         this.fname = fname
         this.lname = lname
         console.log('inside constructor')
      }
      set rollno(newRollno){
         console.log("inside setter")
         this.rno = newRollno
      }
   }
   let s1 = new Student(101,'Sachin','Tendulkar')
   console.log(s1)
   //setter is called
   s1.rollno = 201
   console.log(s1)
</script>

Example 2: javascript class

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);

console.log(square.area); // 100

Example 3: javascript es6 class

class MyClass {
  constructor() {
    this.answer = 42;
  }
}

const obj = new MyClass();
obj.answer; // 42

Example 4: es6 class example

class Polygon { 
   constructor(height, width) { 
      this.height = height; 
      this.width = width; 
   } 
}

Example 5: es6 class example

var Polygon = class { 
   constructor(height, width) { 
      this.height = height; 
      this.width = width; 
   } 
}

Example 6: class declaration in javascript

class NameOfClass {
//class declaration first letter should be capital it's a convention
  obj="text";
  obj2="some other text";
}
//always call class with "new" key word
console.log(new NameOfClass);