JavaScript new.target meta Property
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: