Friday, April 14, 2017

Finally we have classes in ES6


Classes creation and usage in ES5 was a pain. In ES6 we have class keyword and we can create methods and constructor on this class.

Note:This feature would not make JavaScript an object oriented language .These are syntax sugar over functions (Prototype over inheritance language)


Simple class with constructor

Here we are creating a class which accepts firstName and lastName as constructor
"use strict"
//create a class
class Person{
    constructor(firstName,lastName){
        this.firstName =firstName;
        this.lastName=lastName;

        console.log(this.firstName,this.lastName);
    }
}
//create an instance of the class
var person = new Person("Prathap","Kudupu");

Output
C:\Development\NodeProjects\vanilanode>node  class.js
Prathap Kudupu


Classes with methods

In this example we are creating a class with a method
"use strict"
//create a class
class Person{
    constructor(firstName,lastName){
        this.firstName =firstName;
        this.lastName=lastName;
     }
    //method to get age
    get getfullName(){
        //return using string interpolation
        return `${this.firstName}  ${this.lastName}`;
    }
}
//create an instance of the class
var person = new Person("Prathap","Kudupu");
console.log(person.getfullName);
Output
C:\Development\NodeProjects\vanilanode>node  class.js
Prathap  Kudupu

Extending class

In this example we are inheriting from base class .In the base class we are using super keyword to call the base method.
Note: Base and the child has the same method name
class Parent {
    constructor(parent)
       {  
           this.parent=parent 
        }
       //Call base class method
         getfullName(){
         console.log(`${this.parent} :From Base `)
    }
}

class Child extends Parent {
     getfullName(){
        //Call base class method
       super.getfullName();
         console.log(`${this.parent} :From child `)
    }
}
//Create an instance of the child class
var child = new Child("Prathap");
child.getfullName();
Output
C:\Development\NodeProjects\vanilanode>node  class.js\
Prathap :From Base
Prathap :From child

No comments:

Post a Comment