What exactly does the term "new.target" refer to?

The ECMAScript 2015 specification references the term new.target a total of three times - once in section 14.2.3:

Although Contains typically does not analyze most function forms, it is specifically used to identify new.target, this, and super usage within an ArrowFunction.

and two more instances in section 14.2.16:

An ArrowFunction doesn't establish local bindings for arguments, super, this, or new.target. References to arguments, super, this, or new.target inside an ArrowFunction should be resolved within its lexical environment.

MDN discusses this concept briefly but with incomplete information.

It appears that Babel does not currently support new.target, as syntax errors arise when using it in various functions (arrow functions included).

What exactly is new.target and how can it be correctly employed?

Answer №1

The specification does not explicitly mention it, but the syntax definitions include it with spaces as new . target. This expression is known as NewTarget, and you will encounter this term multiple times.

NewTarget is considered one of the meta properties and can be located in §12.3.8.

Its primary function is to fetch the current value of the [[NewTarget]] from the existing (non-arrow) function environment. This value is established when a function is invoked, similar to how the this binding operates. As per §8.1.1.3 Function Environment Records:

If this Environment Record was created by the internal method [[Construct]], then [[NewTarget]] represents the [[Construct]] parameter newTarget. Otherwise, it defaults to undefined.

One significant aspect is that it allows us to determine whether a function was called as a constructor or not.

However, its true purpose lies beyond this. What exactly is it then? It plays a crucial role in ES6 classes by enabling inheritance from built-in objects rather than just serving as syntactic sugar. When a class constructor is invoked using new X, the this value remains uninitialized - the object is not created until the constructor body is initiated. The creation occurs during the super() call within the super constructor where internal slots are generated. The instance should inherit from the .prototype of the original constructor, which is where newTarget comes into play. It holds the outermost constructor that received the new call during super() invocations. You can trace this flow in the specifications, but essentially, it is always the newTarget passed into the OrdinaryCreateFromConstructor procedure instead of the currently executing constructor - for example, in step 5 of §9.2.2 [[Construct]] for user-defined functions.

This explanation might be lengthy; perhaps an example would illustrate better:

class Parent {
    constructor() {
        // Implicit (derived from the `super` call)
        //    new.target = Child;
        // Implicit (due to no extension in `Parent`):
        //    this = Object.create(new.target.prototype);
        console.log(new.target) // Child!
    }
}
class Child extends Parent {
    constructor() {
        // `this` is uninitialized (would throw error if accessed)
        // Implicit (due to the `new` call):
        //    new.target = Child 
        super(); // this = Reflect.construct(Parent, [], new.target);
        console.log(this);
    }
}
new Child;

Answer №2

This feature is primarily designed to improve the detection of constructor calls without using new.

According to a source at :

new.target serves as an implicit parameter present in all functions. It plays a role in constructor calls similar to what this does in method calls.

To illustrate, I can use it in the following way:

function Foo() {
  if (!new.target) throw "Foo() must be called with new";
  ...
}

Although there are more intricacies and scenarios where this feature proves beneficial, we'll end the discussion here.

Interested readers can refer to some meeting notes on new.target at .

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

By clicking the button, you can add an item to select2

Utilizing the select2 tag style in my Drupal YAML form allows users to easily locate and add various items. These items come with both images and titles on the same page, accompanied by a button next to each image. My goal is to enable users to click the b ...

Leverage the AJAX Search Lite Plugin within the top navigation of your WordPress website's header file

I am interested in utilizing the "AJAX Search Lite 3.0.6" plugin within my WordPress Theme. Plugin Link After implementing the shortcode, I noticed that it was not appearing on the navigation bar as expected: <body> <!-- Header --> & ...

Utilize ngx-filter-pipe to Streamline Filtering of Multiple Values

Need assistance with filtering an array using ngx-filter-pipe. I have managed to filter based on a single value condition, but I am unsure how to filter based on multiple values in an array. Any guidance would be appreciated. Angular <input type="text ...

Combining Multiple Arrays into a Multidimensional Array

I'm struggling to find information on how to combine multiple arrays of the same length into a multidimensional array. For example, I have three arrays: array1 = [value1a1, value2a1, value3a1]; array2 = [value1a2, value2a2, value3a2]; array3 = [value ...

Is there a way to automatically send users to a different PHP file once they click "submit"?

I need to redirect to a different php file named index2.php. The username and password values are already set as follows: Username=sid, Password=yeaoklogin. When the user clicks on the Login button, they should be redirected to a page called index2.php. ...

Ways to Manage modals responses as services in AngularJS

I am a beginner in the world of JavaScript and AngularJS. I am fascinated by some of the concepts within JS, like trying to create a modal service using the example I found online. I am eager to delve deeper into what exactly is happening under the hood, e ...

Issue encountered while trying to define a global variable within a JavaScript Class

I'm currently working on setting up a page variable that can be utilized by my Scroller class for implementing infinite scrolling. It's crucial for this variable to have global scope, as it needs to retain its value outside of the ajax function. ...

Utilize JavaScript to iterate through two sets of numbers

I am currently working on a project that requires me to iterate through two continuous number ranges: 1 to 5 and 10 to 15. This is the code I'm using: var X = []; for (i = 1; i < 6; i++) { X.push(i); } for (i = 10; i < 16; i++) { X.push(i ...

"Problem with the Hide/Show Load feature: it's not functioning

After a user submits a form, my script shows 2 divs and hides 1 div. The form's target is an Iframe on the same page. I am looking to delay the Hide/Show events until the Iframe loads. I was successful in accomplishing this with a loading animation, ...

How can I change the nested Material UI component style from its parent component?

I am currently incorporating a component from an external library into my project. However, I am facing limitations in customizing its style, especially when it comes to a button that is using material ui styles. Upon inspecting the element, I can see that ...

When evaluating code with eval, properties of undefined cannot be set, but the process works seamlessly without

Currently, I am attempting to utilize the eval() function to dynamically update a variable that must be accessed by path in the format myArray[0][0[1][0].... Strangely enough, when I try this approach, I encounter the following error: Uncaught TypeError: ...

Connecting via web sockets through SSL is not functioning properly

My Web Socket functions correctly in both the localhost and production environments (https://www.example.com). However, upon deploying the same code to the pp environment (), I encounter the error message: WebSocket handshake - Unexpected response code: 4 ...

React- hiding div with hover effect not functioning as expected

I'm having trouble using the :hover feature in CSS to control the display of one div when hovering over another, it's not functioning as expected. I've successfully implemented this on other elements, but can't seem to get it right in t ...

Is your jQuery .on function failing to properly detect click events?

Seems like I'm missing something here. Why is the .on function not functioning as expected in this code snippet? <html> <head> </head> <body> <button type="button" class="close" data-test="test">TEST BUTTON< ...

"Attempting to use a Chrome Extension to apply inline styles is not producing

Despite my attempts to search on Google, I have been unable to find a solution. I am currently working on developing a Chrome extension with the specific goal of changing/inserting the style.display property for one or more elements. This task would norma ...

SOLVING the issue of page flicker in SVELTE

Within the application below, I am experiencing a peculiar page flicker effect that is often associated with AJAX requests. However, in this scenario, the cause is not AJAX-related but rather a conditional statement that triggers the rendering of different ...

What is the method to retrieve the local filepath from a file input using Javascript in Internet Explorer 9?

I'm experiencing some issues with the image-preview function on IE9, similar to the example photo shown. This method is not functioning properly and throwing an error in IE9, while it works perfectly fine in IE6-8. I am looking for a way to retrieve ...

What is causing the premature termination of the for loop?

I am currently utilizing Node.js (with nodemon as the server) to upload an excel file, parse its contents, and then send each row to a MongoDB database. The total number of rows in the array is 476, however, the loop seems to stop at either 31 or 95 withou ...

Ways to transfer a value between two different card elements

I have designed a component with three div cards side by side using bootstrap. The first card displays a list of products, and my intention is that when a product is clicked, the details should appear in the second card on the same page. However, this fun ...

Leveraging Next.js ISR to pass extra information to the getStaticProps function from the getStaticPaths

Inside SingleBlogPost.jsx, the code for generating blog pages by their slug is as follows: export async function getStaticPaths() { const res = await fetch("http://localhost:1337/api/posts"); let { data } = await res.json(); const paths = data.map(( ...