Home  >  Article  >  Web Front-end  >  How does the \"new.target\" meta property facilitate ES6 class inheritance?

How does the \"new.target\" meta property facilitate ES6 class inheritance?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 04:37:02497browse

How does the

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 Parent constructor uses "new.target" to access the Child constructor.
  • The Child constructor uses "new.target" to determine that it was called with "new," even though the super() call is made before the "this" value is initialized.
  • This allows the Child constructor to correctly inherit from the Parent prototype.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn