您没有在规范中找到它,因为在语法定义中它以空格(如)编写
new.target。表达式的名称是
NewTarget,您会在周围多次找到该术语。
NewTarget是第一个所谓的元属性,可以在§12.3.8中找到。
其唯一目的是检索当前(非箭头)功能环境的[[NewTarget]]值的当前值。它是在调用函数时(非常类似于
this绑定)并根据[§8.1.1.3 函数环境记录设置的值]:
如果此环境记录是通过 [[Construct]]内部方法创建的,则[[NewTarget]]是[[Construct]]
newTarget参数的值。否则,其值为
undefined。
因此,一方面,最终使我们能够检测一个函数是否被称为构造函数。
但这不是其真正目的。那是什么呢?这是ES6类不仅是语法糖,而且还允许我们从内置对象继承的方式的一部分。当您
class通过调用构造函数时
newX,该
this值尚未初始化-
输入构造函数主体时尚未创建该对象。它确实是在
super()调用期间由超级构造函数创建的(当应该创建内部插槽时这是必需的)。不过,该实例仍应继承自
.prototype最初调用的构造函数的,这就是
newTarget
发挥作用的地方。它确实包含在
new调用期间接收到调用的“最外层”构造函数
super()调用。您可以在规范中一直遵循它,但是基本上它始终
newTarget不是当前执行的构造函数,它确实会传递给[
OrdinaryCreateFromConstructor过程例如,在[第9.2.2节 [[Construct]]的步骤5中供用户定义职能。
长文本,也许是一个更适合的示例:
class Parent { constructor() { // implicit (from the `super` call) // new.target = Child; // implicit (because `Parent` doesn't extend anything): // this = Object.create(new.target.prototype); console.log(new.target) // Child! }}class Child extends Parent { constructor() { // `this` is uninitialised (and would throw if accessed) // implicit (from the `new` call): // new.target = Child super(); // this = Reflect.construct(Parent, [], new.target); console.log(this); }}new Child;


