Today I have learned class constructor in javascript

 Class Construtor

The constructor method is a special method of a class for creating and initializing an object instance of that class.

There are some additional syntax restrictions:

  • A class method called constructor cannot be a gettersetterasync, or generator.
  • A class cannot have more than one constructor method.

Description

A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object.

Using new on a class goes through the following steps:

  1. (If it's a derived class) The constructor body before the super() call is evaluated. This part should not access this because it's not yet initialized.
  2. (If it's a derived class) The super() call is evaluated, which initializes the parent class through the same process.
  3. The current class's fields are initialized.
  4. The constructor body after the super() call (or the entire body, if it's a base class) is evaluated.

Within the constructor body, you can access the object being created through this and access the class that is called with new through new.target. Note that methods (including getters and setters) and the prototype chain are already initialized on this before the constructor is executed, so you can even access methods of the subclass from the constructor of the superclass. However, if those methods use this, the this will not have been fully initialized yet. This means reading public fields of the derived class will result in undefined, while reading private fields will result in a TypeError.

import React, { Component } from "react";
export default class Project extends Component  {
    constructor(props){
        super(props);
        this.state={
           
        js:["react.js"],
       
        }
    }
    render(){

 
        return (
    <div>
        <h2>{this.state.js.map((a)=>(a))}</h2>
        </div>
        )
    }}
OUTPUT:


Comments

Popular posts from this blog

Building a Full-Stack Student Management System with React.js and NestJS

Today I have solved the problem in javascript

Today I have solved problem in javascript