Reflect.construct()

The static method Reflect.construct enables the invocation of a constructor while accommodating a flexible number of arguments. Additionally, it provides the capability to define an alternative prototype.

Syntax

Example

Reflect.construct(target, argumentsList[, newTarget])

Parameter

target : It is the target function to call.

argumentsList: This refers to an object resembling an array that defines the parameters with which the target function is intended to be invoked.

newTarget: This refers to a constructor that is intended to be utilized through its prototype. It is also relevant to the new.target operator. In cases where newTarget is absent, it will be regarded as a target.

Return

This technique generates a fresh instance of the specified target (or newTarget if it exists), configured by the target acting as a constructor with the provided parameters.

Exceptions

This exception will raise a TypeError if either target or newTarget do not qualify as constructors.

Example 1

Example

const a = new Array(1,2,3);
const b = Reflect.construct ( Array, [1,2,3] );
console.log(a);
console.log(b);

Output:

Output

[1, 2, 3]
 [1, 2, 3]

Example 2

Example

function func1(a, b, c) {
  this.sum = a + b + c;
}
const args = [1, 2, 3];
const object1 = new func1(...args);
console.log(object1.sum);

Output:

Example 3

Example

function func1(a, b, c) {
  this.sum = a + b + c;
}
function func2(a, b, c) {
  this.sum = a + b + c;
}
const args2 = [1, 4, 3];
const args = [1, 2, 3];
const object1 = new func1(...args);
const object2 = Reflect.construct(func2, args2);
console.log(object2.sum);
console.log(object1.sum);

Output:

Input Required

This code uses input(). Please provide values below: