How to Check If a Javascript Function Was Called Using new Operator

javascript
Published on May 20, 2020

The new.target property can be used to detect whether a function was invoked as a constructor using the "new" operator, or just called normally.

If the function was called using the "new" operator then new.target refers to the constructor or function. For normal function calls new.target will be undefined.

function myFunc() {
	if(new.target === undefined)
		console.log('Normal function call');
	else
		console.log('Function called using new');
}

// "Function called using new"
new myFunc();

// "Normal function call"
myFunc();

new.target property can be useful when we have a function that behaves like a class, and we don't want it to be called as a normal function.

function myFunc() {
	if(new.target === undefined)
		throw new Error('Function not called using new');
}

try {
	myFunc();
}
catch(error) {
	// "Function not called using new"
	console.log(error.message);
}
Comments
Loading Comments