1

I am trying to create a function in javascript which can't be called as constructor like lets say if function is function SomeFunction(){}, on calling it like new SomeFunction() it should throw an exception but calling it without new should work.

Is there a way to achieve this?

Gautam
  • 815
  • 6
  • 15

3 Answers3

2

Use new.target. This is a special property, which is set when the function is called as constructor. See the following example.

function test() {
  if (new.target) {
    throw new Error('Can not call as constructor');
  }
  
  return 'test';
}

console.log(test());
console.log(new test());
31piy
  • 23,323
  • 6
  • 47
  • 67
2

You can also use an es6 arrow => function for this, as they are not allowed as constructor functions.

let SomeFunction = ()=>{ console.log("called");}
SomeFunction();
//Error for arrow function
new SomeFunction();
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
1

The constructor call creates an instance, so you can check if an instance is not created.

function SomeFunction () {
 if(this instanceof SomeFunction)
  throw('constructor called');
 console.log('function called')
}

SomeFunction();

new SomeFunction()
AZ_
  • 3,094
  • 1
  • 9
  • 19