Open In App

JavaScript new.target meta Property

Last Updated : 14 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The new.target pseudo-property let us detect whether a function or constructor is called with the help of new operator or not.

Syntax:

new.target

The following example demonstrates the meta property.

Example 1: In this example, the function is called without the new operator.

HTML




<!DOCTYPE HTML>
<html>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
  
    <p>
        JavaScript | new.target metaKey property
    </p>
      
    <button onclick="Geeks();">
        click here
    </button>
      
    <p id="GFG_DOWN"></p>
  
    <script>
        var el_down = document
                .getElementById("GFG_DOWN");
  
        function Fun() {
            if (!new.target) {
                throw 
    'Fun() is called without new operator';
            }
        }
        function Geeks(event) {
            try {
                Fun();
            } catch (e) {
                el_down.innerHTML = e;
            }
        
    </script>
</body>
  
</html>


Output:

Example 2: In this example, the function is called with the new operator.

HTML




<!DOCTYPE HTML>
<html>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p>
        JavaScript | new.target metaKey property
    </p>
  
    <button onclick="Geeks();">
        click here
    </button>
      
    <p id="GFG_DOWN"></p>
  
    <script>
        var el_down = document
                .getElementById("GFG_DOWN");
        class Person {
            constructor(name) {
                this.name = name;
                if (!new.target) {
throw 'Function is called without new operator';
                }
                else {
throw 'Function is called with new operator';
                }
            }
        }
        function Geeks(event) {
            try {
                var p = new Person('GFG');
            } catch (e) {
                el_down.innerHTML = e;
            }
        
    </script>
</body>
  
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads