JS: Reflect.construct

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2015)

Reflect.construct(C, [args])

same as new C(args).

C is a Constructor, args are arguments.

  • Reflect.construct is like the new (operator) but in a functional notation.

💡 TIP: This is useful for functional programing. For example, apply this function to a array of construct, to create many objects.

const xarray = [ [3, "n3"], [4, "n4"]];
console.log( Reflect.construct ( Map, [ xarray ] ) );
// Map(2) { 3 => "n3", 4 => "n4" }
console.log(Reflect.construct(Date, []));
// 2025-01-12T00:36:07.677Z
Reflect.construct(C, [args], C2)
  • Use constructor C to create an object with args, but use constructor C2 to set the parent.
// prototype object
const proto1 = Object.create(Object.prototype);
proto1.kk = "this is proto1";

// constructor
function C1(x) {
  this.name = x;
}
C1.prototype = proto1;

// HHHH------------------------------

// prototype object
const proto2 = Object.create(Object.prototype);
proto2.kk = "this is proto2";

// constructor
function C2(x) {
  this.name = x;
}
C2.prototype = proto2;

// HHHH------------------------------

// create a object using constructor C1, but set prototype via constructor C2
const xjj = Reflect.construct(C1, ["aa"], C2);

console.log(xjj);
// { name: "aa" }

console.log(Reflect.getPrototypeOf(xjj) === proto2);
// true