Example of class in Javascript ES6

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Here is an example of a class with constructor in Javascript ES6…

example of es6 class

The class name “Animal” is typically capitalized.  The instance variable “person” is not.  You instantiate a class with the “new” keyword and passing into it the argument for the constructor.  The constructor function is run whenever a class is instantiated.  And it is always called “constructor”.

this.name is a property of the class “Animal”.  It’s value is different for each instance.  It’s value is set by the constructor to whatever value was passed into it.  Then “this.name” can be used by other methods within the class.

Note that the method “sayHello” does not require the use of the “function” keyword.

Class Getters and Setters

You can add getters and setters to a class like this…

class getter and setter

Anytime you assign to or retrieve from “name” property, you are invoking the setter and the getter respectively.  This means that you can do something every time a property is set.  In our example, we capitalize the word.

Within the getter and setter method, we store the value in another variable that starts with an underscore.

Note that the constructor also calls the setter, because we are assigning something to “this.name”.   This is evidenced by the output being capitalize.  If constructor was assigning “this._name”, then the setter will not be called.

And if we assign another value to “name” like this …

class

The setter is called.

Static Class Method

You can have a static class method where you can call it without needing to instantiate an instance of the class…

static class method

Extending Classes

Without changing the Animal class, we now create a Dog class that extends the Animal class like this…

extending class

In the constructor, we use “super” to call the constructor of the parent class.  In addition, we set an additional property called “age”.

In Dog, we override the parent’s “sayHello” method — displaying something different for Dogs.

More ES6 features here.