Reflect.construct Builds Instances With newTarget

Call Reflect.construct with a different newTarget to borrow a constructor while producing an instance of a subclass prototype.

JavascriptData Integrity

Code

javascriptsnippet
31 lines
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  describe() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

class Point3D extends Point {
  constructor(x, y, z) {
    super(x, y);
    this.z = z;
  }

  describe() {
    return super.describe() + ' z=' + this.z;
  }
}

// Reflect.construct(target, args, newTarget):借用构造器但换原型
const p = Reflect.construct(Point, [1, 2], Point3D);
console.log('prototype is Point3D:', Object.getPrototypeOf(p) === Point3D.prototype);
console.log('describe:', p.describe());
console.log('z is undefined:', p.z === undefined);

// 对照:普通 new 只产出 Point 实例
const plain = new Point(3, 4);
console.log('plain:', plain.describe(), '| instance of Point3D:', plain instanceof Point3D);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

prototype is Point3D: true
describe: (1, 2) z=undefined
z is undefined: true
plain: (3, 4) | instance of Point3D: false

What the code does

The working surface is the classes Point and Point3D — everything else is wiring.

Module-level bindings hold the data — plain — with no function scope in between.

Applying it

Running the file prints labeled results such as prototype is Point3D:, describe:, z is undefined: — each operation’s effect is visible in the output.

Statements that matter

return '(' + this.x + ', ' + this.y + ')';
return super.describe() + ' z=' + this.z;

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. Its state lives in module-level bindings: `plain`.