Home > Article > Web Front-end > How does the \"new.target\" meta property facilitate ES6 class inheritance?
Understanding "new.target"
The ECMAScript 2015 specification introduces a meta property known as "new.target," which is used within non-arrow functions to determine whether the function was called as a constructor.
Definition and Purpose
"new.target" refers to the first meta property and is formally defined in §12.3.8 of the spec. Its sole purpose is to retrieve the current value of a function's "[[NewTarget]]" internal value. This value is set when the function is called, similar to the "this" binding.
According to §8.1.1.3 Function Environment Records, the "[[NewTarget]]" value is set to the "[[Construct]]" newTarget parameter if the function is called as a constructor. Otherwise, its value remains undefined.
Importance for ES6 Classes
"new.target" plays a crucial role in the implementation of ES6 classes, allowing them to inherit from built-in objects. When calling a class constructor using "new," the "this" value is not yet initialized. However, when the super() method is called, the object is created and set to inherit from the ".prototype" of the "newTarget" constructor.
Example
The following example demonstrates how "new.target" is used in class inheritance:
class Parent { constructor() { // Implicit from 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 uninitialized (and would throw if accessed) // Implicit from new call: new.target = Child super() // this = Reflect.construct(Parent, [], new.target) console.log(this) } } new Child
In this example:
The above is the detailed content of How does the \"new.target\" meta property facilitate ES6 class inheritance?. For more information, please follow other related articles on the PHP Chinese website!