The term "new.target" appears sparingly in the ECMAScript 2015 specification (14.2.3 and 14.2.16), raising questions about its purpose. Interestingly, its full name is NewTarget, found in §12.3.8.
NewTarget is a meta property that retrieves the current value of the [[NewTarget]] within the current non-arrow function environment. When a function is called, a [[NewTarget]] value is assigned, similar to the this binding.
Previously, detecting if a function was called as a constructor was not explicitly supported. However, NewTarget solves this by revealing whether the [[Construct]] internal method created the Environment Record. According to §8.1.1.3, if the Environment Record was created by [[Construct]], [[NewTarget]] holds the value of the [[Construct]] newTarget parameter. Otherwise, it remains undefined.
While syntactic sugar, ES6 classes offer true inheritance. This is where NewTarget plays a crucial role. When calling a class constructor using new X, the this value is initially unset. The super() call within the constructor creates the object but inherits from the .prototype of the originally called constructor.
NewTarget captures the outermost constructor that received the new call. It is not the currently executing constructor. This value is what gets passed into the OrdinaryCreateFromConstructor procedure, ensuring that the instance correctly inherits from the desired prototype.
To illustrate, consider the following classes:
<code class="javascript">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;</code>
In this example, NewTarget allows the Parent class to recognize that it was called as a constructor through the Child class. The Child class then utilizes this information during its super() call to properly establish inheritance.
The above is the detailed content of How does `new.target` help us understand inheritance in ES6 classes?. For more information, please follow other related articles on the PHP Chinese website!