...

/

JavaScript Constructor Functions

JavaScript Constructor Functions

Introduction to JavaScript constructor functions.

Background

We know what OOPs are and their class-based and/or prototype-based approach. The challenge when using OOPs is creating a general mechanism to generate custom objects. In this lesson, we will use functions to construct objects, also called constructor functions. This is the best approach to implement prototype-based OOPs.

Constructor functions

Constructor functions, or object constructor functions, contain blueprints to a type of object that has properties and methods to generate objects. All objects created from a constructor function will have the same properties and methods but not necessarily the same values.

Syntax

Let’s look at the syntax of a constructor function.

Press + to interact
function FunctionName(parameter1, parameter2,...){
//all the properties of the object are initialized here
//functions to be provided by objects are defined here
}

As we can see from above:

  • The keyword function defines the function.

  • The constructor function name should be capitalized, as per convention, just like FunctionName in the ...