Modern Class Syntax in JavaScript

In previous article, we saw how to create classes, constructors, properties and methods.

In Next Generation JavaScript, we skip constructor function and use Arrow functions for our methods. We can directly declare parameters.

Let’s see below example:

class Person{
    name = "Akanksha";
    address = "Delhi";  

  getPersonDetails = () => {
    console.log("Name: " + this.name);
    console.log("Location: " + this.address);
  }
}

class Student extends Person{
  cls = "12th";

  getStudentDetails = () => {
    console.log("Class: " + this.cls);
  }
}

const student = new Student();
student.getPersonDetails();
student.getStudentDetails();

Class in ReactJS

  • Components are categorized in two types
    • Functional Components
    • Class-based Components
  • In previous article, we have seen only Functional Components. In this article, we will learn about Class-based components.
  • Class Components must be a JavaScript class
  • The Class should extend React.Component
  • Must define a render method that returns some amount of JSX

Let’s see how to create a class and display it on the page.

  • We will create a new app named classdemo
  • Take the reference from Environment Setup – ReactJS article
  • Delete all the files from src folder and create two new files in it: index.js and Comments.js. As of now, I am displaying the static values.
Comments.js

Paste the below code in this file

import React from 'react';
import { Comment } from 'semantic-ui-react';

class Comments extends React.Component {
    render() {
        return (
            <Comment>
                <Comment.Content>
                    <Comment.Author as='a'>Akanksha</Comment.Author>
                    <Comment.Metadata>                  
                        <div>Today</div>
                    </Comment.Metadata>
                    <Comment.Text>Nice Post!!</Comment.Text>
                    <Comment.Actions>
                        <Comment.Action>Reply</Comment.Action>
                    </Comment.Actions>
                </Comment.Content>
            </Comment>
        );
    }
}

export default Comments;
index.js

Paste the below code in this file

import React from 'react';
import ReactDOM from 'react-dom';
import { Comment } from 'semantic-ui-react';
import Comments from './Comments';

class App extends React.Component {
    render() {
       return (
        <Comment.Group>
             <Comments />
        </Comment.Group>
       );
    }
 }

ReactDOM.render(<App />, document.getElementById('root'));

Start the app from NodeJS Command Prompt.
Below is how the above application looks

Inheritance in TypeScript

  • Inheritance is a concept in which we reuse the properties and methods of another class or interface, hence no need to rewrite the code again and again.
  • We use extend keyword to inherit other interfaces and classes.
  • We use an existing class to create a new class.
  • The class that is used to create the new class is called as parent class/super class. The newly created class is called as child class/sub class.
  • Child class inherits all the fields and methods from the parent class except the private fields and constructor.
  • Inheritance with Interface is explained in another article.

Syntax

class childClass extends parentClass{}

Below is an example of class inheritance

class Vehicle{
    model:string;
    color:string;
}
class Car extends Vehicle{
    fuelType:string;
}

class Maruti extends Car{
    customername:string;
    purchasedOn:string;
    
    constructor(custName:string, date:string, ){
        super();
        this.customername = custName;
        this.purchasedOn = date;   
    }
    purchaseDetails():void {
        console.log(this.customername + " purchased a car on " + this.purchasedOn);
        console.log("Model of the car: " + this.model+ "; Color: " + this.color + "; Fuel Type: " + this.fuelType);
    }
}
var car = new Maruti("Akanksha","28th Dec, 2018");
car.model = "Maruti Suzuki Dzire"
car.fuelType = "Diesel";
car.color = "Silver";
car.purchaseDetails();

Below is the output of above code

Other Related Articles

Classes in TypeScript
Interfaces and Classes in TypeScript
Interfaces in TypeScript
Access Modifiers
Method Overriding

Interface and Classes in TypeScript

Let’s implement Interfaces to Class.
Below is an example

interface IVehicle{
    model:string;
    color:string;
}
interface ICar extends IVehicle{
    fuelType:string;
}

class Car implements ICar{
    customername:string;
    purchasedOn:string;
    mycar1:ICar;
    model:string;
    color:string;
    fuelType:string;
    
    constructor(custName:string, date:string, car1:ICar){
        this.customername = custName;
        this.purchasedOn = date;   
        this.mycar1 = car1;
    }
    purchaseDetails():void {
        console.log(this.customername + " purchased a car on " + this.purchasedOn);
        console.log("Model of the car: " + this.mycar1.model+ "; Color: " + this.mycar1.color + "; Fuel Type: " + this.mycar1.fuelType);
        // Below line of code will only return undefined
        //console.log("Model of the car: " + this.model+ "; Color: " + this.color + "; Fuel Type: " + this.fuelType);
    }
}
var carDetails:ICar = {model:"Hyundai Creta", color:"White", fuelType:"Petrol"};
var car = new Car("Akanksha","28th Dec, 2018", carDetails);
car.purchaseDetails();

Below is the output of above code

Other Related Articles

Interfaces in TypeScript
Classes in TypeScript
Inheritance in TypeScript

Classes in TypeScript

  • TypeScript is an Object Oriented Language and hence we can create classes, interfaces, objects etc. in TypeScript.
  • We can create objects of the classes, hence classes encapsulates the data for the object.
  • We use class keyword to create classes in TypeScript.
  • Class name follows the rules same as variables.
  • Class definition includes:
    • Fields: A field is a variable declared in a class. They represents the properties of the object creates using the class. These fields can only be used by the objects of that class and their scope is limited to that class only.
    • Constructors: Constructors are used to allocate memory for the objects of the class. We can also use constructors to assign values to the fields of the object. Please note that we can define only one constructor in a class, multiple constructor declaration is not allowed. A constructor is a function which can be parameterized.
    • Functions: These are the operations or actions that an object can perform. They are also referred as methods.
  • We do not use var keyword to declare fields in a class.
  • this keyword refers to the current instance of the class. If the field name and constructor’s parameter names are same, we can use this keyword with fields to remove the ambiguity.
  • We use new keyword to create an object of the class.
    • Syntax: var objectName = new ClassName();
  • In above piece of code, ClassName() invokes the constructor of the class. If the constructor has parameters, we can pass the value of those parameters from here. For example: var objectName = new ClassName(value1, value2,….);
  • We access the field and methods of the class using the object followed by dot(.). For example,
    • to access field: objectName.field1;
    • to access function: objectName.functionName(parameterValue1, parameterValue2,…);

Syntax for creating class

class className{
  // class fields and methods
}

Below is an example, where we create a class, define fields, constructor and function. We then create an object of this class, initialize the fields and then invoke the function.

class Car{
    customername:string;
    purchasedOn:string;

    constructor(custName:string, date:string){
        this.customername = custName;
        this.purchasedOn = date;
    }
    purchaseDetails():void {
        console.log(this.customername + " purchased a car on " + this.purchasedOn);
    }
}
var car = new Car("Akanksha","28th Dec, 2018");
car.purchaseDetails();

Below is the output of above code

Other Related Articles

Interfaces in TypeScript
Interface and Classes in TypeScript
Inheritance in TypeScript
static keyword
instanceof Operator
Access Modifiers

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started