You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于JavaScript Reflect.construct中newTarget参数作用的困惑

Understanding 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 target function—its entire code body will execute, using the new instance as the this context.
  • Instance identity & prototype chain: This is controlled by the newTarget function—the new instance’s internal [[Prototype]] will point to newTarget.prototype, and its constructor property will inherit from that prototype.

Step-by-Step Breakdown of Your Code

When you run Reflect.construct(Parent, [], Child):

  1. A new empty object is created, with its prototype set to Child.prototype (all thanks to the newTarget = Child parameter).
  2. The Parent constructor is invoked, with this new object as the this value. That’s why:
    • The line this.parent = "Parent" adds the parent property directly to the instance.
    • You see the log "This is parent."—the code inside Parent runs in full.
  3. Since Parent doesn’t return an explicit object value, the newly created instance is returned as the final result.
  4. The instance’s constructor property comes from Child.prototype (which by default points back to Child), hence why your output shows constructor: 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:53:07