javascript / expert
Snippet
Metaprogramming with Reflect.construct
Reflect.construct allows you to invoke a constructor while specifying a different 'new.target'. This is essential for advanced inheritance scenarios and proxy-based factory patterns where you need the object to inherit from one class's prototype while being initialized by another's constructor.
snippet.js
1
2
3
4
5
6
7
8
class Base { constructor() { console.log(new.target.name); } }class Extended {}// Create an instance of Base, but with Extended as the new.targetconst instance = Reflect.construct(Base, [], Extended);console.log(instance instanceof Base); // trueconsole.log(instance instanceof Extended); // true
nodejs
Breakdown
1
Reflect.construct(Base, [], Extended);
Calls Base's constructor, but sets the prototype of the new object to Extended.prototype.
2
new.target.name
In the constructor, new.target refers to the third argument passed to Reflect.construct.