Home > Web Front-end > JS Tutorial > What is \'new.target\' and How Does It Work in ES6 Classes?

What is \'new.target\' and How Does It Work in ES6 Classes?

Linda Hamilton
Release: 2024-10-30 03:52:03
Original
761 people have browsed it

 What is

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

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!

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