Skip to content

JavaScript constructor function | Example code

  • by

JavaScript constructor function is a special method used to create and initialize an object instance. Use the new keyword to create an object from a constructor function.

constructor() { /* ... */ }
constructor(argument0) { /* ... */ }
constructor(argument0, argument1) { /* ... */ }
constructor(argument0, argument1, ... , argumentN) { /* ... */ }

Recommended naming constructor functions with an upper-case first letter.

JavaScript constructor function

Simple example code of object constructor function.

<!DOCTYPE html>
<html>
<body>

  <script>
    // constructor function
    function Person () {
      this.name = 'John',
      this.age = 23
    }

    // create an object
    const p1 = new Person();
    p1.name = "Mike"
    p1.age = "100"

    console.log(Person)
    console.log(p1)
</script>

</body>
</html> 

Output:

JavaScript constructor function

Create Multiple Objects with Constructor Function

// create objects
const p1= new Person();
const p2= new Person();

JavaScript this Keyword

The this keyword is used in a constructor function,where it refers to the object when the object is created.

// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John

Constructor Function Parameters

You can also create a constructor function with parameters.

Adding a Property to a Constructor

Person.nationality = “English”;

To add a new property to a constructor, you must add it to the constructor function:

function Person(first, age) {
  this.firstName = "AAA";

  this.age = 25;
  this.nationality = "XYZ";
}

Adding a Method to a Constructor

Constructor function can also define methods:

function Person(first, age) {
    this.firstName = "AAA";
    this.age = 25;
    this.nationality = "XYZ";

    this.name = function() {
      return this.firstName;
    };
  }

Built-in JavaScript Constructors

 new String()    // A new String object
new Number()    // A new Number object
new Boolean()   // A new Boolean object
new Object()    // A new Object object
new Array()     // A new Array object
new RegExp()    // A new RegExp object
new Function()  // A new Function object
new Date()      // A new Date object 

Do comment if you have any doubts or suggestions on this Js constructor topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *