Skip to content

JavaScript object constructor | Function

  • by

JavaScript object constructor function is used to create objects. The constructor property returns a reference to the Object constructor function that created the instance object.

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

JavaScript object constructor

Simple example code to create an object from a constructor function use the new keyword.

<!DOCTYPE html>
<html>
<body>
  <script >
    // constructor function
    function Person () {
      this.name = 'John',
      this.age = 25
    }

    // create an object
    const person = new Person();

    console.log(person)
    console.log(typeof(person))
  </script>
</body>
</html>

Output:

JavaScript object constructor function

JavaScript Constructor Function Parameters

<!DOCTYPE html>
<html>
<body>
  <script >
    // constructor function
    function Person (pname, page, pgender) {

    // assigning  parameter values to the calling object
    this.name = pname,
    this.age = page,
    this.gender = pgender,

    this.greet = function () {
      return ('Hi' + ' ' + this.name);
    }
  }

    // creating objects
    const person1 = new Person('John', 23, 'male');
    const person2 = new Person('Mike', 25, 'female');

    // accessing properties
    console.log(person1.name); // "John"
    console.log(person2.name); // "Mike"
  </script>
</body>
</html>

Adding a Property to a Constructor

You cannot add a new property to an object constructor the same way you add a new property to an existing object. To add a new property to a constructor, you must add it to the constructor function:

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

Adding a Method to a Constructor

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

Do comment if you have any doubts or suggestions on this Js object 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading