JavaScript — Object Oriented Programming using ES6

March 31, 2018 0 Comments

JavaScript — Object Oriented Programming using ES6

 

 

ES6(ECMAScript2015) is a major upgrade to JavaScript. In this article we will learn the new way of achieving Object Oriented concepts like class, object, static properties, constructor and inheritance with super and extends in JavaScript.

act of writing helps us to remember things better
  • Object is a thing which can be seen or touched and in software we try to represent the same real-life thing with object.
  • Object Oriented Programing is nothing but code around that object.
  • Class is not an object, it’s like blueprint which can generate objects. So, class helps to set the classification of objects with its properties and capabilities.
  • Any number of instance can be created from a class, each instance is called Object.
class Car { 
  /* Properties and Actions /
}
let figo = new Car(); 
console.log(typeof Car);            // function
console.log(typeof figo); // object
console.log(figo instanceof Car); // true

In the above code snippet, we can see the typeof class Car still return as function because behind the scene JavaScript still works with function only.

  • Constructor is just a function which gets called automatically when we create an instance from the class.
  • Instance variables get created and initialized using constructor.
  • Instance variables are nothing but called properties of the object.
  • Methods are again functions which attached with instance and all instance created from the same class will have those methods or actions.
  • Accessing properties and methods inside class, we need this keyword.
class Meetup {
constructor(name, location) {
this.name = name;
this.location = location;
}
  start() {
console.log(this.name + 'Meetup ' + 'is started at ' + this.location);
}
}
let jsMeetup = new Meetup('JS', 'Blr');
let ngMeetup = new Meetup('Angular', 'Noida');
jsMeetup.start(); //JSMeetup is started at Blr
ngMeetup.start(); //AngularMeetup is started at Noida

Explanation of above code snippet:

  • The instance jsMeetup created using new keyword and class Meetup has been called like function.
  • we can pass arguments to the class as well like any other function and behind the scene, it will call to the constructor function for initializing the instance variables name and location.
you can go through blog JavaScript — All about this and new keyword to understand in-depth working of this and new keyword.
  • Each instance of the class will have its own properties which gets created at constructor but Class can have also it’s own properties.
  • The class only properties are called Static Properties.
  • Same holds true for Static methods as well.
class Meetup {
constructor(name, location) {
this.name = name;
this.location = location;
}
    start() {
console.log(this.name + 'Meetup ' + 'is started at ' + this.location);
}
    static getAddress() {
console.log('Returned Address');
/
this.location will return undefined /
console.log('City: '+ this.location );
}
}
Meetup.admin = "Adam";
Meetup.getMembers = function () {
console.log(Meetup.admin+ ' Returned Members');
}
let jsMeetup = new Meetup('JS', 'Blr');
console.log(Meetup.admin);   // Adam
console.log(jsMeetup.admin); // undefined
Meetup.getMembers();         // Adam Returned Members
jsMeetup.getMembers(); // TypeError: jsMeetup.getMembers is not a function
Meetup.getAddress();         // Returned Address
jsMeetup.getAddress(); // TypeError: jsMeetup.getAddress is not a function

Explanation of above code snippet:

  • The instance jsMeetup cannot access the class only methods i.e. static methods getMembers() and getAddress(). Same with static properties as well like admin is static property.
  • We can put label as static in-front of methods and properties inside the class definition to make it accessible to class only or we can add it later to the class as well like Meetup.getMembers = function(){...}.
  • The scope of this keyword is current execution context of the method. In case of static method, the execution context can never be class instance or object. That’s the reason this.location of static method getAddress() prints undefined.
class Meetup {
constructor(name) {
this._name = name;
}
    get name() {
// Validation can happen on data
return this._name;
}
    set name(val) {
// Validation can happen on data
this._name = val;
}
}
let meetup = new Meetup('JS');
console.log("meetup Name: " + meetup.name); // meetup Name: JS
meetup.name = 'Angular';
console.log("meetup Name: " + jsMeetup.name); // meetup Name: Angular

Explanation of above code snippet:

  • With getter and setter, will have more control on object properties after initialization with constructor.
  • We can do required validation on data within get and set method before setting or getting the value.
  • We can see in the above code that the instance property name is _name but we are using it as meetup.name and its working fine because of getter and setter methods.
class Meetup {
}
class techMeet extends Meetup {
}
class sportMeet extends Meetup {
}
let js = new techMeet();
console.log(js instanceof techMeet);  // true
console.log(js instanceof Meetup); // true
console.log(js instanceof Object); // true
  • The above code snippet is new way of achieving inheritance in JavaScript using extends and class keyword.
  • We can see that object js is instance of class techMeet and Meetup both because class techMeet extends parent class Meetup.
class Meetup {
constructor() {
console.log("inside Meetup constructor");
}
}
class techMeet extends Meetup {
constructor() {
super();
console.log("inside techMeet constructor");
}
}
let js = new techMeet();
// inside Meetup constructor
// inside techMeet constructor

Explanation of above code snippet:

  • Inside constructor function of child class techMeet, we have to call super() method to call the parent constructor first otherwise JavaScript will throw error.
  • super() method is nothing but constructor function of Parent class.
  • super() call is must in constructor of derived class whether explicit presence of parent constructor exists or not.
class Meetup {
constructor(organizer) {
this.organizer = organizer;
}
}
class techMeet extends Meetup {
constructor(organizer) {
super(organizer);
// this.organizer = 'NG';
}
}
let js = new techMeet('Mr. JS');
console.log(js.organizer); // Mr. JS

Explanation of above code snippet:

  • We can pass the argument from child constructor to parent constructor through super() method like above code snippet.
  • We can override the parent class properties inside constructor of child class.
class Meetup {
organise() {
console.log('Organising Meetup');
}
    static getMeetupFounderDetails() {
console.log("Meetup Founder Details");
}
}
class techMeet extends Meetup {
organise() {
//super.organise();
console.log('Organising techMeet');
super.organise();
}
    static getMeetupFounderDetails() {
console.log("techMeet Founder Details");
super.getMeetupFounderDetails();
}
}
let js = new techMeet();
js.organise();
/ Output: 
Organising techMeet
Organising Meetup /
techMeet.getMeetupFounderDetails();
/ Output: 
techMeet Founder Details
Meetup Founder Details */

Explanation of above code snippet:

  • Child class can access the methods of parent class using super object like super.organise().
  • Similarly static methods of child class can access the static method of parent class with help of super object.

Syntax changes in ES6 and new features are helping to write better, cleaner and lesser code to achieve the object-oriented concepts in JavaScript. It’s helping to bridge the gap between prototypal JavaScript and classical programmers.


Tag cloud