Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Invoking a Function with a Function Constructor

If a function invocation is preceded by the new keyword, it becomes a constructor invocation.

It may seem like you’re creating a new function, but since JavaScript functions are objects, you’re actually creating a new object.

Example

// This is a function constructor:
function myFunction(arg1, arg2) {
  this.firstName = arg1;
  this.lastName  = arg2;
}

// This creates a new object
const myObj = new myFunction(“John”“Doe”);

// This will return “John”
myObj.firstName;

A constructor invocation creates a new object that inherits the properties and methods from its constructor.

The this keyword in the constructor does not have a predefined value. Instead, the value of this will be the new object created when the function is invoked.