How To Create Constructor Method In Class Using JavaScript

admin_img Posted By Bajarangi soft , Posted On 10-10-2020

In Class we can create constructor method using java script. so today we see what is the use of constructor method in class

How To Create Constructor Method In Class Using JavaScript

Class Syntax

Use the keyword class to create a class.

Always add a constructor() method.

Add any number of additional methods.
 

Syntax

class ClassName {
    constructor() { ... }
    method_1() { ... }
    method_2() { ... }
    method_3() { ... }
 }
}
 

Example(1)

A class definition for a class named "Car":

class Car {
    constructor(name, year) {
        this.name = name;
        this.year = year;
    }
}


Now you can use the Car class to create Car objects:

myCar1 = new Car("Ford", 2014);
myCar2 = new Car("Audi", 2019);
 

The constructor method is called automatically when a new object is created.


The Constructor Method

The constructor method is a special method:

  • It has to have the exact name "constructor"
  • It is executed automatically when a new object is created
  • It is used to initialize object properties

It if you do not define a constructor method, JavaScript will add an empty constructor method.


Compelete Code For Creating Constructor Method In Class Using JavaScript

<!DOCTYPE html>
<html>
<head>
    <title>How To Create Constructor Method In Class Using JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <br>
    <div class="text-center">
        <h1 id="color" style="color: tomato">How To Create Constructor Method In Class Using JavaScript</h1>
    </div>

    <div class="well">
        <h2 id="demo1"></h2>
        <h2 id="demo2"></h2>
        <h2 id="demo3"></h2>

        <script>
            class Car {
                constructor(name, year) {
                    this.name = name;
                    this.year = year;
                }
            }

            myCar = new Car("Ford", 2014);
            document.getElementById("demo1").innerHTML =
                myCar.name + " " + myCar.year;
        </script>
    </div>
</div>
</body>
</html>

 

Related Post