constructor in js code example

Example 1: javascript constructor function

function ClassMates(name,age){
  this.name=name;
  this.age=age;
  this.displayInfo=function(){
    return this.name + "is " + this.age + "year's old!";
  }
}

let classmate1 = new ClassMates("Mike Will", 15);
classmate.displayInfo(); // "Mike Will is 15 year's old!"

Example 2: constructor in js

A constructor is a function that creates an instance of a class
  which is typically called an “object”. In JavaScript, a constructor gets 
  called when you declare an object using the new keyword.
  The purpose of a constructor is to create an object and set values if 
  there are any object properties present.

Example 3: js constructor object

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

var car1 = new Car('Eagle', 'Talon TSi', 1993);

console.log(car1.make);
// expected output: "Eagle"

Example 4: javascript constructor object

function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

Example 5: constructors javascript

function Bird() {
  this.name = "Albert";
  this.color = "blue";
  this.numLegs = 2;
}
/*
This constructor defines a Bird object with properties name, color, and
numLegs set to Albert, blue, and 2, respectively.
Constructors follow a few conventions:
-Constructors are defined with a capitalized name to distinguish them from
other functions that are not constructors.

-Constructors use the keyword this to set properties of the object they will
create. Inside the constructor, this refers to the new object it will create.

-Constructors define properties and behaviors instead of returning a value as
other functions might.
*/

Example 6: how to create a constructor in javascript

function Bird() {
  this.name = "Albert";
  this.color  = "blue";
  this.numLegs = 2;
}

let blueBird = new Bird();