JavaScript new target | Metaproperty

  • by

JavaScript new target meta property is used to detect whether a function or constructor was called using the new operator. The new.target consists of the new keyword, a dot, and target property. The new.target is available in all functions.

new.target

JavaScript new target

Simple example code determines at runtime whether a function or constructor was called using the new keyword or not.

functions

Detect whether a function was called with new as a constructor.

function Foo() {
  if (!new.target) { throw 'Foo() must be called with new' }
  console.log('Foo instantiated with new')
}

new Foo()  // logs "Foo instantiated with new"
Foo()      // throws "Foo() must be called with new"
<!DOCTYPE html>
<html>
<body>
  <script>
    function Person(name) {
      if (!new.target) {
        throw "Must use new operator with Person";
      }
      this.name = name;
    }

    try {
      Person();
    } catch (e) {
      console.log(e);

    }
  </script>
</body>
</html> 

Output:

JavaScript new target

Constructors

<script>
   class Person {
    constructor(name) {
      this.name = name;
      console.log(new.target.name);
    }
  }

  class Employee extends Person {
    constructor(name, title) {
      super(name);
      this.title = title;
    }
  }

  let john = new Person('John Doe'); 
  let lily = new Employee('Lily Bush', 'Programmer'); 
</script>

Do comment if you have any doubts or suggestions on this JS pseudo-property topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.