JS: Reflect.construct
New in JS2015.
Reflect.construct(C, [a1, a2, etc])
-
same as
new C(a1, a2, etc)
.Reflect.construct
is like the Operator “new” but in a functional notation.- This is useful for functional programing. For example, apply this function to a array to generate a array objects.
console.log( Reflect.construct ( Date, [] ) ); // 2020-09-09T04:25:05.378Z
Reflect.construct(C, [a1, a2, etc], C2)
-
Use C2's prototype mechanism for the result object's prototype. That is, use C to create the object, but use C2 to set the parent.
New Target Argument
Here's a example using the third argument.
const proto1 = Object.create ( Object.prototype); proto1.k1 = "this is proto1"; const proto2 = Object.create ( Object.prototype); proto2.k2 = "this is proto2"; // ----------- function C1 (x) { this.name = x; } C1.prototype = proto1; // ----------- function C2 (x) { this.name = x; } C2.prototype = proto2; // ----------- const r1 = Reflect.construct ( C1 , ["something"], C2 ); console.log( r1 ); // { name: "something" } console.log( Reflect.getPrototypeOf ( r1 ) === proto2); // true