Home > Article > Web Front-end > How does `new.target` Enable Inheritance and Differentiate Constructor Calls in ES6 Classes?
Despite being mentioned only three times in ECMAScript 2015 specification, "new.target" is a meta property defined in §12.3.8.
"NewTarget" retrieves the value of the [[NewTarget]] internal property of the current function environment. This value is set when a function is called as a constructor.
If a function was invoked using new, new.target will reference the constructor function used to create the new instance. This enables developers to distinguish between constructor and normal function calls.
"NewTarget" plays a crucial role in ES6 classes. When a class constructor is invoked with new, it returns this, which is initially uninitialized. However, super() initializes this by calling the parent constructor while passing new.target as an argument.
This mechanism allows classes to inherit from built-in objects, such as Array or Map. By passing new.target to the parent constructor, the correct prototype chain is established, ensuring that the new instance inherits from the appropriate prototype object.
Consider the following class structure:
class Parent { constructor() { // new.target = Child (from super() call) console.log(new.target); } } class Child extends Parent { constructor() { // new.target = Child (from new call) super(); console.log(this); } } new Child;
In this example, new.target is:
The output will be:
Child { __proto__: Child.prototype }
This demonstrates how new.target can be used to differentiate between constructor and normal function calls, as well as to manage inheritance in ES6 classes.
The above is the detailed content of How does `new.target` Enable Inheritance and Differentiate Constructor Calls in ES6 Classes?. For more information, please follow other related articles on the PHP Chinese website!