Constructor in JavaScript

Mar 06, 2019

A constructor is a function in JavaScript. Its not the function declaration  what separates a function from constructor but the function invocation. It's an ordinary function that is used with the new operator to produce a specialized type of object.

A constructor is useful when you want to create multiple similar objects with the same properties and methods. A constructor names  start with a capital letter. Its a convention that should be followed.

function Car()
{

}
var myCar = new Car();

The last line of code creates one instance of Car and assign to the variable myCar. Car Constructor not doing anything but myCar is still instance of it.

When a constructor is invoked, the following special actions take place:

  • A new empty object is created.
  • This object is passed to the constructor as the this parameter, and thus becomes the constructor’s function context.
  • In the absence of any explicit return value, the new object is returned as the constructor’s value.

All objects inherit a constructor property from their prototype:

var s = new String("Book");
s.constructor === String;      // true

"Book".constructor === String; // true

var o = new Object();
o.constructor === Object;      // true

var o = {};
o.constructor === Object;      // true

var a = new Array();
a.constructor === Array;       // true

[].constructor === Array;      // true

Instanceof Operator

To check whether an object is an instance of another one, we use the instanceof operator:


myCar instanceof Car \\ true


myCar instanceof String \\ false

Another way to check  the type of an instance is using the constructor property. All object instances have a constructor property that point to the constructor function that created it.

myCar.constructor == Car; \\true

Now in javascript a constructor is used when you are doing or working with Prototype objects or Object Oriented Javascript. it can be viewed as a normal function which initializes a value or sets the default values.

function person(first, last, age, eye)

{ 
    this.firstName = first;
    
    this.lastName = last;
    
    this.age = age; 
    
    this.eyeColor = eye;
}
var myFather = new person("John", "Doe", 50, "blue");

var myMother = new person("Sally", "Rally", 48, "green");

So in the above Eg : person(first, last, age, eye) is your Constructor Function.

new person("John", "Doe", 50, "blue") - in this line we are calling the Constructor function with a “new” keyword which creates an Object of the Constructor.

and Finally:

var myFather = new person("John", "Doe", 50, "blue"); 

Here var myFather is my Object of person() constructor.

"new" keyword is necessary

If we accidentally forget to use  "new" keyword then it will take the global object instead of taking newly created object.


function Book(name , year)
{

    console.log(this); //window
    
    this.name=name;
    
    this.year=year;
  }
  
  var myBook1 = Book("Javascript",2015);
  
  conole.og(myBook1 instanceof Book);//false
  
  var myBook = new Book("Node js",2010);
  
  console.log(myBook2 instanceof Book);// true

In the above code, When we call the Book constructor without new keyword,  "this" inside the Book constructor will be equal to Window.

Note that in strict mode this code throws an error because strict mode protects us from accidentally calling a constructor without the new keyword.

Object.define property

object.define property use inside the constructor to help in necessary property setup.

Example 1:

function Book(name) { 

  Object.defineProperty(this, "name",
  { 
  
      get: function()
      { 
      
        return "Book: " + name; 
        
     },  
     
     configurable: false  
     
   }); 
   
}


var myBook = new Book("JavaScript");
console.log(myBook.name);    // Book: JavaScript



// we cannot delete the name property because "configurable" is set to false
delete myBook.name;    
console.log(myBook.name);    // Book: JavaScript



// but we can change the value of the name property
myBook.name = "Testable JavaScript";
console.log(myBook.name);    // Book: Testable JavaScript

Example 2:

const object1 = {};

Object.defineProperty(object1, 'property1', 
{
  value: 42,
  
  writable: false
});

object1.property1 = 100;// throws an error in strict mode

console.log(object1.property1);// expected output: 42

In object.define property we don't include method and properties. we only use getter and setter method . Getter is used when the value is to read and getter return the value. Setter is used when the value is written and setter received the value which assigned to the function.

This constructor allows us to set or change the name property of instances, but we are not allowed to delete it.

Object literals and Constructor

There are nine inbuilt function in javascript: Object(),  Array(), String(), Number(), Boolean(), Date(), Function(), Error(), RegExp(). We can use object literal and constructor for creating values. Object literals are easier and faster to run because they optimize parse time. Whenever we use simple object it is best to use object literals.



// a string object
// strings have a slice() method 

var obj = new String("book");

obj.slice(0,2);     // "bo"

// same as above
var string = "book";

string.slice(0,2);  // "bo"

There is no difference between these object literals and constructors and we can still call methods on literals. It's because when we call a method on a literal, behind the scene JavaScript converts the literal to a temporary object so that it's possible to use object methods for primitive values, then JavaScript discards the temporary object.

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.