1

Class in ES6

Reading Time: 3 minutes

As we all know JavaScript is an object-oriented language (prototype based). That means classes in JavaScript too is prototype based. The concept of class is not new in JavaScript but the keyword class is new, the keyword class is actually a syntactical sugar over the function and function is first class citizen. Lets see how new feature/syntatic sugar looks

class Animal {
  constructor(animalName, noise) {
    this._animalName = animalName;
    this._noise = noise;
  }
  // constructor(name) {
  //  this.Name = name;
  // }
  //  Uncaught SyntaxError: A class may only have one constructor

  get AnimalName() {
    return this._animalName.toUpperCase();
  }
  get Noise() {
    return this._noise.toUpperCase();
  }
}

In the above snippet code class `Animal` is created with a constructor which accepts two parameters (animalName, noise). Currently class can have only one constructor if you try to have multiple it would throw `SyntaxError`. Next is we have two properties `AnimalName` and `Noise` which doesn’t implement set. So it is like a readonly property

class Animal { }//SyntaxError: Identifier 'Animal' has already been declared

var Animal = class {};//SyntaxError: Identifier 'Animal' has already been declared

If you try to create class with same name you will `SyntaxError`. A class can be created similar to how we create function which is what illustrated in the last line of the code.

var dog = new Animal('dog', 'barks');
console.log(dog.Noise);//BARKS
console.log(dog.name);//Animal
console.log(dog.AnimalName);//DOG

Here an instance is created for the `Animal` class. If you notice dog.Noise returns ‘barks’ where Noise is the property where as dog.name is not property which we created but it returns ‘Animal’. Here class.name is the name of the class which we have not defined but automatically gets included.

console.log(Animal.length);//2

Similarly we didn’t create property ‘length‘ it is automatically included which is actually the number of parameters of class’s constructor

class ClsA{
  constructor(){
  }
}

class ClsB{
  constructor(a, b, c){    
  }
}

class ClsC{
  constructor(a, b, c, d, e){    
  }
}

console.log(ClsA.length);//0
console.log(ClsB.length);//3
console.log(ClsC.length);//5

So it is better not to name static properties with name `name` and `length`

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.