The method Reflect.construct
helps construct a new instance from a constructor function given an array of arguments. It has a functionality similar to the new
operator:
function Employee (firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
let employee1 = new Employee("John", "Doe");
let employee2 = Reflect.construct(Employee, ["Jane", "Doe"]);
// This can also be done with the spread operator:
let args = ["John", "Smith"];
let employee3 = new Employee(...args);
It is generally useful to have an alternative for the new
operator, specially when we have an array of arguments. Even though this particular problem has been alleviated in ES6 with the introduction of the spread operator(...
). (See the last line in the example code above.)