DEV Community

PRIYA K
PRIYA K

Posted on

Constructor in JavaScript

A constructor function is a special function used to create many objects with the same structure.
Curly braces represent an object.
Create many Objects easily.
Each Key-value pair is called Property
Instead of writing many objects manually, we create a blueprint
name constructor functions with an upper-case first letter.

constructor()
Special method inside a class
Runs automatically when object is created

function Person(name, age) {
Enter fullscreen mode Exit fullscreen mode

Explanation
function Person(name, age)

function → keyword to define a function
Person → constructor name
name, age → parameters

Understanding this
this.name = name;
this=>refers to the current object being created

this.name=>creates a property called name inside the object

= name(assigns the value received from the parameter)

Example :

{
   name : "Priya"
}
Enter fullscreen mode Exit fullscreen mode

this.age = age;
creates an age property
stores the value passed to the constructor

object becomes:

{
name : "Priya",
age : 21
}

Steps:

  1. Creates an empty object { }
  2. Sets this to point to that object
  3. Calls the constructor function
  4. Assigns values (name, age)
  5. Returns the object

Instantiating an object constructor
There are two ways to instantiate object constructor,

const object_name = new Object(); 
const object_name = { };
Enter fullscreen mode Exit fullscreen mode
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Saraswathi","g",42,"black")
console.log(myFather.age)
Enter fullscreen mode Exit fullscreen mode

Explanation
In constructor function,'this' has no value
this value = new object value

Property Default Value

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

// Create 2 Person objects
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
console.log(myMother.nationality)
Enter fullscreen mode Exit fullscreen mode

Adding Property to an Object

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

// Create 2 Person objects
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

// Add nationality to first object
myFather.nationality = "English";
console.log(myFather.nationality)
Enter fullscreen mode Exit fullscreen mode

Adding Property to Constructor

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

// Create 2 Person Objects
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

// Will Not Work
Person.nationality = "English";
console.log(Person.nationality)
Enter fullscreen mode Exit fullscreen mode

Add a new property add it to constructor function prototype

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

// Create 2 Person Objects
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

// Add a new Property
Person.prototype.nationality = "English";
console.log(myFather.nationality)
Enter fullscreen mode Exit fullscreen mode

Explanation
Person.nationality =>Property belongs to constructor only.
Person.prototype.nationality => Property shared by all objects.

Constructor Function Methods
can have methods

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

// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");
console.log(myFather.fullName())
Enter fullscreen mode Exit fullscreen mode

Adding method to an object

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

// Create 2 Person objects
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

// Add a Name Method
myMother.changeName = function (name) {
  this.lastName = name;
}

// Change Name
myMother.changeName("Doe");
console.log(myMother.lastName)
Enter fullscreen mode Exit fullscreen mode

Output
Doe

Calling the Method

p1.sayHello();
Enter fullscreen mode Exit fullscreen mode

Output:
My name is Priya and I am 21 years old.

Adding a Method to a Constructor
Adding a new method to a constructor must be done to the constructor function prototype:

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

// Create a Person Object
const myMother = new Person("Sally","Rally",48,"green");

Person.prototype.changeName = function (name) {
  this.lastName = name;
}

// Change Name
myMother.changeName("Doe");
console.log(myMother.lastName)
Enter fullscreen mode Exit fullscreen mode

Built-in JavaScript Constructors

JavaScript has built-in constructors for all objects:
new Object() // A new Object object
new Array() // A new Array object
new Map() // A new Map object
new Set() // A new Set object
new Date() // A new Date object
new RegExp() // A new RegExp object
new Function() // A new Function object

Example

 "";           // primitive string
0;            // primitive number
false;        // primitive boolean

{};           // object object
[];           // array object
/()/          // regexp object
function(){}; // function 
Enter fullscreen mode Exit fullscreen mode

Need to Rememeber

  • The Math() object is not in the list. Math is a global object. The new keyword cannot be used on Math.
  • Use object literals {} instead of new Object().
  • Use array literals [] instead of new Array().
  • Use pattern literals /()/ instead of new RegExp().
  • Use function expressions () {} instead of new Function().

** Simple Real-Life Example**

Constructor = factory machine
Person constructor
|
|---- Person1
|---- Person2
|---- Person3
Each object has same structure but different values.

Why Constructors are Useful
Without constructor:

object1
object2
object3

You must write many objects manually.

With constructor:
Person() → blueprint
|
|---- p1
|---- p2
|---- p3
You can easily create many objects.

Constructor Using Class (Modern Way)

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

let student = new Student("Priya", 22);
console.log(Student);
Enter fullscreen mode Exit fullscreen mode

Constructor Function (Old Way)
Before ES6, constructors were written like this:

function Student(name, age) { 
    this.name = name; 
    this.age = age; 
} 

let student = new Student("Priya", 22);
Enter fullscreen mode Exit fullscreen mode

This still works, but modern JS prefers class syntax.

Concept Meaning
Object Collection of properties
Constructor Blueprint to create objects
this Refers to current object
new Creates a new object
Method Function inside object

Top comments (0)