Ad

Constructor function in JavaScript

JavaScript constructor is used when we want to create many similar objects for multiple users. Constructor functions is similar to normal functions except it start with capital letter and executes with the new operator.

Example 1: Create constructor function for two users.

function Student(name) {
    this.name = name;
    this.age = 30;
}
let user = new Student("Ankit"); //use to call constructor function
console.log(user.name); // Jack
console.log(user.age); // 30

let user2 = new Student("Jordan Walke"); //another object
console.log(user2.name); // Jordan Walke
console.log(user2.age); // 30

Any function is use to create constructor except arrow function as they don't have this. It can be run with new keyword and first letter capital.

We can check whether the constructor function is called with new keyword or without it, using new.target. It returns undefined it is not called without new, and returns function if it is called with new keyword.

function Student() {
    console.log(new.target);
}
Student(); // undefined, without 'new'
new Student(); // function User { ... } with 'new'

We can also make both new and regular calls to do the same, like this:

function Student(name) {
    if (!new.target) { // if you run without new
      return new Student(name); // ...I will add new for you
    }
    this.name = name;
}
let student = Student("Ankit"); // redirects call to new User
console.log(student.name); // Ankit

Above syntax is used to make the syntax more flexible, so that user may call the function with or without new keyword and it still works.

Return from constructors

Constructor is use to initialize value into 'this' and returns automatically, but if return statement is applied then it override it with the returned object.

Example 2: Constructor function with return statement

function Student() {
    this.name = "Ankit";
    return { name: "JavaScript Constructor" };  // returns this object
}
console.log( new Student().name );  // JavaScript Constructor

Example 3: Constructor function with empty return statement

function Student() {
    this.name = "Ankit";
    return;  // returns this object
}
console.log( new Student().name );  // Ankit
Omitting parentheses
let user = new User; // no parentheses
let user = new User(); // same as above statement

Omitting parentheses here is not considered a 'good style', but the syntax is same

Methods in constructors

In Constructor functions we can add not only properties but also the methods.

Example 4: Method in constructor function

function Student(name) {
    this.name = name;
    this.result = function() {
        let a=50;
        let b=60;
        let c=a+b;
        console.log( "Name = " + this.name );
        console.log( "Total Marks = " + c );
    };
}
let student1 = new Student("Ankit");
student1.result();
/* Name = Ankit
Total Marks = 110 */

Question for Practice: Create a constructor function Calculator that creates objects with 3 methods: read(), sum(), mul().

JavaScript Feedback, Questions, Suggestions, Discussion.

Ad: