Creating a simple class in ES6 Javascript

posted in: Javascript | 0

Javascript ES6 allows you to code like a regular OOP languages. Although inner workings of Javascript remains same, it allows more neat code.

Let us go through how to create a simple class in Javascript.

Define a class by using the keyword class and put the class codes under the curly braces.

class MyClass {

}

We can instantiate the object of that class by using new keyword and class name.

let myclass = new MyClass();

 

We can create the constructor with the constructor keyword.

class MyClass {

    constructor(val1, val2) {
        this.name1 = val1;
        this.name2 = val2;
    }
    
}

Now we can instantiate the object with initial values as follows

let myclass = new MyClass("Name1", "Name2");

 

Classes can have methods and those can be accessed by objects

class MyClass {

    hello(name) {
        return "Hello : " + name;
    }

    display() {
        var output;
        output = "Hello  " + this.name1;
        output += "\n Hello : " + this.name2;
        return output;
    }
}

These methods can be accessed by Objects

let myclass = new MyClass("Name1", "Name2");
console.log(myclass.hello("my name"));
console.log(myclass.display());

Static methods are creating using the keyword static

class MyClass {
   
    static myStatic(name) {
        return "Hello : " + name;
    }
  
}

Static methods are accessed using class names instead of object names

console.log(MyClass.myStatic("hello Sttaic"));

 

Setters use the keyword set as prefix followed by method name with a single argument.

Getters use the keyword get as prefix followed by the name with no arguments but a return value.

class MyClass {

    set firstName(value) {
        if (value) {
            this.name1 = value;
        }
    }

    get firstName() {
        return "Hello : " + this.name1.toUpperCase();
    }
}

We can use it on objects like a variable

let myclass = new MyClass("Name1", "Name2");
myclass.firstName = "New Name";
console.log(myclass.firstName);

This is a very simple way to create a class in Javascript and using it. We can use more of the object oriented features too. Those will be covered later.

Leave a Reply