Javascript - Classes in ES6

Introduction

ES6 classes do not work exactly the same way as in other object oriented languages.

A class in ES6 is a function under the hood.

class in ES6 is syntactical sugar over Objects and Prototypes.

This new class keyword in ES6 supports prototype-based inheritance, constructors, super calls, instance, and static methods.

The following code uses the most basic form of class declaration in ES6.

class Car { 
    constructor(brand) { 
        this.brand = brand; 
    } 
} 

const myTesla = new Car("Tesla"); 

console.log(myTesla.hasOwnProperty("brand"));  // true 
console.log(typeof Car);                       // function 

Here, brand is the property assigned on the myTesla object.

This object can be represented in an object literal form as follows:

const myTesla = { 
      brand: "Tesla" 
}; 

The constructor() method is optional, you can declare an empty class like the one in the following example:

class EmptyClass { 

} 

If you don't define a constructor() method inside a class, the JavaScript engine will insert an empty one for you:

class EmptyClass { 

    /* JavaScript inserts an empty constructor: 
     constructor () { } 
    */ 

} 

Class declarations allow you to define methods on a class without the use of a "function" keyword:

class Car { 
        constructor(brand) { 
                this.brand = brand; 
        } 
        start() { 
                console.log(`Your ${this.brand} is ready to go!`); 
        } 
} 

const myTesla = new Car("Tesla"); 

myTesla.start(); 
// Your Tesla is ready to go! 

Here, we defined a start() method inside the class definition, which accesses the brand property of the class using this keyword.

This method gets automatically attached to the class's prototype and hence is non-enumerable.