ES6 Tutorial - Classes
   Jan. 4th,2018
   Ismail Nassor Mbarack

ES6 classes are one of the most awesome syntactic sugar that comes right out of the box.Remember in the past when we wanted to simulate classes, we had to use functions and prototypes but yet wasn't as great as the classes like the way it is in Java, PHP and some other languages?Now that time is over, in ES6 we can define classes, instantiate classes, inherit other classes behaviors and so on just like the way you do in other languages.In fact, your code is still gonna be converted into prototypes and so on but you don't have to be bothered with prototypes at all.All you need is just to define a class, methods and properties, and that's it.Let's take a look at the following example.

NOTE: This tutorial assumes that you already have a knowledge of classes from other languages.

 

class User{
    signup(name,email,gender='M'){
        this.name = name;
        this.email = email;
        this.gender = gender;
    }
    login(){
        console.log(`You logged in as ${this.name}`);
    }
    getInfo(){
        console.log(this.name);
        console.log(this.email);
        console.log(this.gender);
    }
    logout(){
        console.log(`Goodbye....`);
    }
}

let webUsers = new User();
//I didn't add gender on purpose to simulate the default value
webUsers.signup('Ismail','info@isunaslabs.com');
console.log('========User Info========');
webUsers.getInfo();
console.log('========Over========');

 

See from the code above, we simply defined a class and instantiated it and voila, we could use it just like that.Thanks to ES6 that we can even extend classes.

 

class User{
    signup(name,email,gender='M'){
        this.name = name;
        this.email = email;
        this.gender = gender;
    }
    login(){
        console.log(`You logged in as ${this.name}`);
    }
    getInfo(){
        console.log(this.name);
        console.log(this.email);
        console.log(this.gender);
    }
    logout(){
        console.log(`Goodbye....`);
    }
}

class Author extends User{
    postArticle(){
        console.log(`This article was posted by ${this.name}`);
    }
}

let postAuthor = new Author();
console.log('=======test some inherited methods=======');
postAuthor.signup('Lisa','author@example.com','F');
postAuthor.login();
console.log(`=======test Author class's own methods=======`);
postAuthor.postArticle();
postAuthor.logout();

 

Hurraaaaaaay! We could inherit User class properties and use them in the Author class just like that. You'll use it a lot when you use some JavaScript libraries like React JS, With all these class features OOP in JavaScript will never be the same again.