JavaScript - Reflect.construct() 方法
Reflect.construct() 方法用于创建具有给定参数集的构造函数实例。它是 Reflect 对象的一部分,该对象提供了一些用于操作对象及其属性的静态方法。当您在编码时需要动态构建构造函数实例而不知道构造函数名称时,Reflect.construct() 方法非常有用。
语法
以下是 JavaScript Reflect.construct() 方法的语法 -
Reflect.construct(target, argumentList, newTarget)
参数
此方法接受三个参数。下文将对此进行描述 -
target - 调用目标函数。
argumentsList - 它是一个类似数组的对象,用于指定调用目标时应使用的参数。
newTarget - 它是一个可选参数,用于指定要使用其原型的构造函数。
返回值
此方法返回目标的新实例。
示例
示例 1
让我们看下面的示例,我们将在其中创建类的一个实例。
<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>
如果我们执行上述程序,它将在网页上显示一段文本。
示例 2
考虑另一种场景,我们将使用数组原型创建类的实例。
<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>
执行上述脚本后,网页上将显示一段文本。
示例 3
在下面的示例中,我们将创建一个不带任何参数的类实例。
<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>
当我们执行上述脚本时,会弹出输出窗口,显示网页上的文本。

