Introduction
Classes are template used for creating objects, encapsulating data with code to work on that data. Class in Javascript is built on prototype but also it has some syntax that are not shared with ES5 class-like semantic. In the modern JavaScript, there’s a more advanced “class” construct, that introduces great new features which are useful for object-oriented programming.
Defining JS class
Class can be regarded as a type of function, but instead of keyword function, which we normally use for initiate a function, we will use keyword class and the properties are assigned inside constructor method.
class MyClass {
// class methods
constructor() { ... }
method1() { ... }
method2() { ... }
method3() { ... }
...
}
constructor()
The constructor() method is a special method for creating and initializing objects created within a class. Class can have only one constructor per class, so you will not be able to add multiple constructors to one Class and in case you do you will get SyntaxError. This method will be called automatically when a class is initiated and it strictly needs to be named "constructor". In case you dont define constructor, Javascript will automatically add invisible and empty constructor method.
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
extends
The extends keyword is used to create a child class of another or parent class. This means that child class will inherit all methods from parent class. This is useful for code reusability because reusing properties and methods of an already existing class can be really helpfull and we do not duplicate code unnseccarry.
class Student extends User {
constructor(firstName, lastName, age, monthlySallary, user_class, grade) {
super(firstName, lastName, age, monthlySallary);
this.class = user_class;
this.grade = grade;
}
}
static
The static keyword define static methods for classes which are called directly on the class and not on the instance. In order to call static method we do not need to create instance of the class in order to call static method as in case above.
class Car {
constructor(brand) {
this.carname = brand;
}
static hello() { // static method
return "Hello!!";
}
}
mycar = new Car("Ford");
//Call 'hello()' on the class Car and NOT mycar
Car.hello();
super
The super keyword is used to call the constructor of the parent class in order to access parent properties and methods which are defined in constructor of the parent class. In order to understand better concept of the "inheritance" in Object oriented programming you can read this
great articleclass Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}
mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();
Class fields
Private class
Class fields are public by default, but private class members can be created by using a hash # prefix. The privacy encapsulation of these class features is enforced by JavaScript itself.
JavaScript, being a dynamic language, is able to perform this compile-time check because of the special hash identifier syntax, making it different from normal properties on the syntax level.
class PrivateClass {
#confidental;
constructor() {
this.#confidental = 5;
delete this.#confidental; // Syntax error
this.#uknownFeild = 10; // Syntax error
}
}
const instance = new PrivateClass();
instance.#confidental == 10; // Syntax error
Public class
As mentioned above, by default properties in Javascript class are public. Both static and instance public fields are writable, enumerable, and configurable properties so you are able to call it outside declaration and class.
class ClassWithInstance {
someInstance = 'this is instance';
}
class ClassWithStatic {
static someStatic = 'this is static';
}
class ClassWithPublicMethod {
publicMethod() {
return 'This is public method';
}
}
console.log(ClassWithInstance.someStatic); // Output: this is static
console.log(Object.hasOwn(ClassWithStatic, 'someStatic')); // Output: true
const instance = new ClassWithInstance();
console.log(instance.someInstance); // Output: this is instance
Class in Typescript
As traditional Javascript uses functions and prototype-based inheritance, for programmers used to object oriented approach can be a little bit confusing and akward. From ECMAScript 6 Javascript introduced so you can use object-oriented approach as well in Javascript. Typescript allow developers to use it and compile down to Javascript and it will be compatible to every popular browser and platform without having to think about next version of Javascript.
class Animal {
public name: string; //public field
#species: string; //private field
constructor(animalName: string, species: string) {
this.name = animalName;
this.#species = species;
}
move(distance: number = 0) {
console.log(`Animal moved ${distance}m.`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
bark() {
console.log("Woof! ");
}
}
let simba = new Dog("Simba the dog");
let bonnie: Animal = new Dog("Bonnie");
simba.move(); // Output: Animal moved 0m.
simba.bark(); // Output: Woof!
tom.bonnie(34); // Output: Animal moved 34m.
new Animal("Horse").species; // Property 'species' is private and only accessible within class 'Animal'.
Class project Example
About
This is a little example on how you can use classes in Javascript, it is on codesandbox so you can try it, test it and change it in order to better get the concept and usability of the class.