关于JavaScript Reflect.construct中newTarget参数作用的困惑
Reflect.construct Behavior in Your Example Let’s break down exactly what’s happening here, because Reflect.construct has a nuanced behavior that’s easy to misinterpret at first glance.
Core Mechanism of Reflect.construct(target, args, newTarget)
The key thing to grasp is that this method splits two critical aspects of object construction:
- Initialization logic: This is handled by the
targetfunction—its entire code body will execute, using the new instance as thethiscontext. - Instance identity & prototype chain: This is controlled by the
newTargetfunction—the new instance’s internal[[Prototype]]will point tonewTarget.prototype, and itsconstructorproperty will inherit from that prototype.
Step-by-Step Breakdown of Your Code
When you run Reflect.construct(Parent, [], Child):
- A new empty object is created, with its prototype set to
Child.prototype(all thanks to thenewTarget = Childparameter). - The
Parentconstructor is invoked, with this new object as thethisvalue. That’s why:- The line
this.parent = "Parent"adds theparentproperty directly to the instance. - You see the log
"This is parent."—the code insideParentruns in full.
- The line
- Since
Parentdoesn’t return an explicit object value, the newly created instance is returned as the final result. - The instance’s
constructorproperty comes fromChild.prototype(which by default points back toChild), hence why your output showsconstructor: Child().
Clarifying MDN’s Description
MDN’s wording "a new instance of the given target, created by calling it (or newTarget if present) as a constructor" is a bit ambiguous, but it refers to the instance’s identity (not which constructor’s code runs). The instance is "marked" as a Child instance (via prototype and constructor), but its internal state is initialized using the logic from Parent.
A Simple ES5 Simulation
To make this even more concrete, here’s a rough simulation of what Reflect.construct does under the hood:
function simulateReflectConstruct(target, args, newTarget) { // Create instance tied to newTarget's prototype const instance = Object.create(newTarget.prototype); // Run target's constructor logic on the instance const constructedResult = target.apply(instance, args); // If target returns an object, use that; else use the instance return typeof constructedResult === 'object' && constructedResult !== null ? constructedResult : instance; }
This matches exactly what you’re seeing: the instance gets Parent’s properties (from running target.apply), but retains Child’s prototype and constructor identity.
内容的提问来源于stack exchange,提问作者Panda World

