JavaScript·100 questions

QUESTION: What is new.target?

Answer

The special property new.target, introduced in the ES6 standard, is a powerful tool for metaprogramming in JavaScript. The main task of this property is to directly point to the constructor that was called using the new keyword. If a function or class was called normally, without the new operator, the value of new.target will be undefined. This feature makes it easy to determine whether a constructor was called correctly, and if necessary, force it to be called via new or throw an error.

One of the classic practical applications of new.target is implementing abstract classes, which should not have instances directly. You can write a check inside the base class constructor: if new.target equals the abstract class itself, you should initiate an error prohibiting direct object creation, allowing instances to be created only through child subclasses.

It is important to consider the behavior of new.target inside various types of functions. In regular functions and class constructors, it refers to the invoking constructor. However, arrow functions do not have their own new.target property. Inside an arrow function, it is inherited from the outer context, just like the this keyword, which makes the behavior predictable when using nested functions.

Was this answer helpful?

More questions in this topic

Related questions from other topics