ES6 - Reflect.construct() 方法
此方法充当 new 运算符,相当于调用 new target(...args)。
语法
下面给出的语法适用于函数 construct(),其中,
target 是要调用的目标函数。
argumentsList 是一个类似数组的对象,指定应使用哪个参数来调用目标。
newTarget 是应使用其原型的构造函数。这是一个可选参数。如果未向此参数传递任何值,则其值为 targetparameter。
Reflect.construct(target,argumentsList[,newTarget])
示例
以下示例创建一个具有 fullName 属性的 Student 类。该类的构造函数以 firstName 和 lastName 作为参数。如下所示,使用反射创建 Student 类的对象。
<script> class Student{ constructor(firstName,lastName){ this.firstName = firstName this.lastName = lastName } get fullName(){ return `${this.firstName} : ${this.lastName}` } } const args = ['Mohammad','Mohtashim'] const s1 = Reflect.construct(Student,args) console.log(s1.fullName) </script>
上述代码的输出将如下所示 −
Mohammad : Mohtashim