Sunday, November 22, 2015

Introducing "class", "constructor" , "static", "extends" & "super" keywords in JavaScript (ECMAScript 6)

Most devs are familiar with most of these keywords in their favorite languages. Now if your favorite language is JavaScript and you were missing these keywords ECMAScript 6 has introduced following new keywords with a bonus keyword "Constructor", i think no other language has this keyword. Below are the new keywords
  • class
  • constructor
  • static
  • extends
  • super

Although they look very similar to other language constructs they are actually different and JavaScript is still supporting only prototype-based inheritance. Let's discuss each of them 

class:  

Class declarations are also a type of functions and the work almost the same way. A simple class can be defined as below:

Another way to create a class in javascript is by using class expressions as shown below

Constructor:

constructor is a method that is used in order to create the object by use of class keyword. You can only have one function using constructor in your class.

Static:

Same as in other languages(c#) this static method is used to create a function that can be run without instantiating the object of a class. They are mostly used to create utility functions.
 

extends:

This can be used to extend any javascript class. When I tried to create use this method to extend a class as shown below, I got an error:


Javascript ES6 class extend error "Uncaught ReferenceError: this is not defined"

Super: 

In order to get rid of this error all I have to do was call a function super(); super method is used to call the functions of objects parent.

ES6 class constructors MUST call super if they are subclasses and want to access "this" keyword.

So, Just uncomment the super() method in above code and everything will work fine as shown below.

No comments:

Post a Comment