Gareth Redfern developer, cyclist & coffee lover

Constructor Functions In Javascript

Posted by Gareth Redfern
Category: javascript

A constructor function in Javascript handles the initial creation of objects and lets you create more than one object of the same type. They help keep your code DRY so that you don’t repeat yourself.

Its main purpose is to describe how an object should be created and each object created is know as an instance of that object type.

It’s common practice to name your constructor functions with a capital letter, that way you know they are a constructor function and you should then use the new keyword when you create an instance of that object (instantiate).

var Lesson = function(title,referenceNumber) {

  this.title = title;
  this.referenceNumber = referenceNumber;

}

var lesson = new Lesson('Javascript Basics', '#657859');

The keyword this inside a constructor function references the new instance of the object. So in the example above the title and referenceNumber are passed in and assigned to the new object which is created.