JavaScript Classes.

 

Understanding JavaScript Classes.





Classes were introduced in ECMAScript 2015 to replace the already limited but functional prototype-based inheritance. While classes do introduce powerful Object Oriented programming capabilities to JS, they are simply “special functions” similar to how you can define function declarations or function expressions. To declare a class, we use to class keyword.

class User {
constructor(username, age, address) {
this.username = username;
this.age = age;
this.address = address;
}
}
Here we create a new class User with three properties: username, age and address. The constructor is a special method that initializes an object created by a class automatically, so each time we need to make a new User, we would have to pass in their username, age and address. One important aspect of classes is, unlike function declarations, classes are hoisted. This means that you cannot create an object before accessing it, otherwise the code will throw a ReferenceError.

Constructors and super() keyword

A constructor is a special method for creating and initializing objects that have been created with a specific class. There can only be one constructor and a SyntaxError will be thrown if a class embodies more than one constructor. If a class does not have a constructor, a default one will be assigned and used.

The super keyword is used in JavaScript to access and call functions on an object’s parent. The super.prop and super[expression] expressions are valid in defining methods for both classes and object literals.

class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
getArea() {
return this.width * this.height;
}
}
class Square extends Rectangle {
constructor(length) {
super(length, length);
}
}

Conclusion.

Classes strengthen the already existing OOP concept that could be implemented by the prototype feature and introduces new powers like mix-ins and species (topic for another day). You’ll build upon further by learning TypeScript to fully unlock the power of these new features. OOP is still a powerful concept when designing Business Intelligence applications and using structured architecture.

Thank you for going through this article. For insights, questions and requests please reach out to the comment section below. :)



Comments