JavaScript new.target Tutorial

In this section, we will learn what the new.target is and how to use it in JavaScript.

What is new.target in JavaScript?

Functions and constructors can be called in two ways:

  • Directly (although constructors created via `class` syntax disallows it).
  • As part of creating an object (via new, super etc.)

Sometimes, it’s important to know how our function was called. Perhaps we want to make a class abstract (only allow instances to be created using subclasses), or final (don’t allow any inheritance to happen from a class). Perhaps we want a function that changes what it does depending on whether it was called via `new` or directly.

In those cases, we can use the `new.target` to find out how the function was called. If the function was called directly (not via `new`), `new.target` will return the value `undefined`.

Example: using new.target in JavaScript

function exam(){
  console.log(new.target);
}
exam();
new exam();

Output:

undefined

ƒ exam(){

console.log(new.target);

}

How Does JavaScript new.target Work?

As you can see from the example above, if the current function was the direct target of the `new` operator, `new.target` will refer to the current function. But if we call the function directly (without the word new) we will get the value undefined if we call the `new.target`.

Example: JavaScript new.target statement

class Base{
  constructor(){
    if (new.target == Base){
      throw new Error ("You can't create an object directly from the Base class");
    }

  }
}
class Sub extends Base{
  constructor(){
    super();
  }
}
new Base();

Output:

Uncaught Error: You can't create an object directly from the Base class

Another example:

class Simple{
        constructor(){
          console.log(new.target);
        }
      }
      new Simple();

Output:

class Simple{
        constructor(){
          console.log(new.target);
        }
      }

If the target constructor is called via the `super` keyword, the `new.target` refers to the subclass constructor that was the target of the `new`.

Example:

class Base{
        constructor(){
          console.log(new.target);
        }
      }
      class Sub extends Base{
        constructor(){
          super();
        }
      }
      new Sub();

Output:

class Sub extends Base{
        constructor(){
          super();
        }
      }

Reference book:

JavaScript the New Toys

Author: T.J Crowder

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies