Reflect.construct() JavaScript

The JavaScript Reflect.construct() method invokes a constructor with a variable number of arguments. It also provides the option to set a different prototype.

Syntax:

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

Parameters: target: It represents the object that has to be invoked. argumentsList: It represents the parameters for the function. newTarget: It represents the constructor whose prototype should be used. It is an optional parameter.

Return: It returns a new object of the target (or newTarget, if present), initialized by the target as a constructor with the given argument list.

Note: It will throw a TypeError, if target or newTarget are not constructors.

Example 1:

<!DOCTYPE html>
<html>
<body>
<script>
const n = Reflect.construct ( Array, [55,44,33,22,11] );
document.write(n);
</script>
</body>
</html>

Example 2:

<!DOCTYPE html>
<html>
<body>
<script>
function testFunc(a, b, c) {
this.sum = a + b + c;
}
const args = [10, 12, 30];
const object1 = new testFunc(...args);
const object2 = Reflect.construct(testFunc, args);
document.write(object2.sum);
document.write("</br>");
document.write(object1.sum);
</script>
</body>
</html>
Please follow and like us:
Content Protection by DMCA.com