JS Coding Questions Logo
JS Coding Questions
#416💼 Interview💻 Code

How to detect if a function is called as constructor

Advertisement

728x90

You can use new.target pseudo-property to detect whether a function was called as a constructor(using the new operator) or as a regular function call.

1. If a constructor or function invoked using the new operator, new.target returns a reference to the constructor or function.

2. For function calls, new.target is undefined.

javascript
1function Myfunc() {
2
3if (new.target) {
4  console.log("called with new");
5} else {
6  console.log("not called with new");
7}
8}
9
10new Myfunc(); // called with new
11
12Myfunc(); // not called with new
13
14Myfunc.call({}); // not called with new

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 73

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
416of476