what is constructor in javascript class code example

Example 1: javascript class constructor

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

const person = new Person("John Doe", 23);

console.log(person.name); // expected output: "John Doe"

Example 2: javascript class constructor

class Cat {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
      
      	get fullname() {
          return this.getFullName()
        }
        getFullName() {
            return this.name + ' ' + this.age
        }
    }

    const run = document.getElementById("run");
    run.addEventListener("click", function () {
        let Skitty = new Cat('Skitty', 9);
        let Pixel = new Cat('Pixel', 6);
        console.log(Skitty.getFullName()); // Skitty 9
      	console.log(Skitty.fullname); // Skitty 9 => shorter syntax
        console.log(Skitty, Pixel); 
      // Object { name: "Skitty", age: 9} Object {name: "Pixel", age:6}
    })

Example 3: what is constructor in java

A constructor is a special method used to initialize objects in java.
we use constructors to initialize all variables in the class 
when an object is created. As and when an object
is created it is initialized automatically with the help of 
constructor in java.
  
We have two types of constructors:
Default Constructor
Parameterized Constructor

public classname(){
}
public classname(parameters list){
}

Tags:

Java Example