JavaScript - Reflect.construct() Method
The Reflect.construct() method is used to create instances of a constructor function with a given set of arguments. It is a part of the Reflect object, which offers several static methods for manipulating objects and their properties. When you need to dynamically build an instance of a constructor function without knowing the constructor's name when coding, the Reflect.construct() method is very useful.
Syntax
Following is the syntax of JavaScript Reflect.construct() method −
Reflect.construct(target, argumentsList, newTarget)
Parameters
This method accepts three parameters. The same are described below −
target − It is a call to the target function.
argumentsList − It is a array like object specifying the arguments with which the target should be called.
newTarget − It is a optional parameter, for the constructor whose prototype to be used.
Return value
This method returns a new instance of the the target.
Examples
Example 1
Let's look at the following example, where we are going to create an instance of the class.
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
class x {
constructor(a) {
this.a = a;
}
}
const instance = Reflect.construct(x, ['WELCOME']);
document.write(instance.a);
</script>
</body>
</html>
If we execute the above program, it will displays a text on the webpage.
Example 2
Consider another scenario where we are going to create a instance of the class using array prototype.
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
class x {
constructor(a) {
this.a = a;
}
}
const instance = Reflect.construct(x, ['TutorialsPoint'], Array);
document.write(instance instanceof Array, " < br > ");
document.write(instance.a);
</script>
</body>
</html>
On executing the above script, it will displays a text on the webpage.
Example 3
In the following example, we are going to create a instance of the class without any arguments.
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
class x {
constructor() {
this.Company = 'Maserati';
}
}
const car = Reflect.construct(x, []);
document.write(JSON.stringify(car));
</script>
</body>
</html>
When we execute the above script, the output window will pop up, displaying the text on the webpage.