0
var Test = function () {
    console.log("something");
}

I want to call this function only by putting "new" i.e new Test(); It should throw error when called in this way. Test();

MK-89
  • 3
  • 3

1 Answers1

0

The new.target property lets you detect whether a function or constructor was called using the new operator. In constructors and functions instantiated with the new operator, new.target returns a reference to the constructor or function. In normal function calls, new.target is undefined. (shamelessly copied from MDN)

var Test = function () {
    if (!new.target) throw 'Test() must be called with new';
    console.log("something");
}

ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target

REDDY PRASAD
  • 833
  • 1
  • 8
  • 24