Understanding "new.target" in ECMAScript 2015
In the ECMAScript 2015 specification, the keyword "new.target" is introduced and briefly mentioned three times. While MDN provides some context, it remains somewhat vague.
What is "new.target"?
"new.target" is a meta property, also known as NewTarget. It retrieves the current value of the [[NewTarget]] internal slot of the non-arrow function environment. This value is set when a function is invoked with the "new" keyword.
Purpose of "new.target"
Its primary purpose is to determine whether a function was called as a constructor or not. Additionally, it plays a crucial role in the implementation of ES6 classes.
How ES6 Classes Utilize "new.target"
When an ES6 class constructor is invoked via "new X", the "this" value is not initialized. The object is not yet created. However, the instance should inherit from the .prototype of the originally called constructor.
"new.target" tracks the "outermost" constructor that received the "new" call during super() invocations. The OrdinaryCreateFromConstructor procedure uses "new.target" instead of the currently executed constructor to ensure the correct inheritance.
Example:
<code class="javascript">class Parent { constructor() { console.log(new.target); // Child! } } class Child extends Parent { constructor() { super(); console.log(this); } } new Child;</code>
In this example, "new.target" will output "Child" within the Parent constructor, indicating that it was called with the "new" keyword.
The above is the detailed content of What is \'new.target\' and How Does It Work in ES6 Classes?. For more information, please follow other related articles on the PHP Chinese website!