Home > Web Front-end > JS Tutorial > How does `new.target` Enable Inheritance and Differentiate Constructor Calls in ES6 Classes?

How does `new.target` Enable Inheritance and Differentiate Constructor Calls in ES6 Classes?

Mary-Kate Olsen
Release: 2024-11-03 11:53:29
Original
517 people have browsed it

How does `new.target` Enable Inheritance and Differentiate Constructor Calls in ES6 Classes?

Understanding "new.target"

Definition and Location

Despite being mentioned only three times in ECMAScript 2015 specification, "new.target" is a meta property defined in §12.3.8.

Purpose and Usage

"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.

Significance for ES6 Classes

"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.

Example

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;
Copy after login

In this example, new.target is:

  • Child in the Parent constructor (called from the super() call)
  • Child in the Child constructor (called with new)

The output will be:

Child
{ __proto__: Child.prototype }
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template