0

Can we create a function in javascript which can be called only by new keyword? Somebody ask me how to introduce such restriction in javascript and what are the usages.

Will appreciate if somebody can answer on usage of this restriction as well.

jiten
  • 5,005
  • 3
  • 12
  • 8
  • 3
    A little research goes a long way, so please, use stack overflow to ask for help, but in all honestly, it feels like you're being a little bit lazy here. It's really not that hard to Google things. –  Jul 03 '18 at 13:12
  • 2
    [`new.target`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target). – ASDFGerte Jul 03 '18 at 13:14

2 Answers2

3

The new.target property lets you detect whether a function or constructor was called using the new operator:

function Foo() {
  if (!new.target) throw 'Foo() must be called with new';
}

try {
  Foo();
} catch(e) {
  console.log(e);
  // expected output: "Foo() must be called with new"
}

This may be helpful in next cases:

  1. When call function Foo() it is implicit that new object instance will be created, but with new keyword - it is explicit. As result code is better to read/use/maintain/etc.

  2. When you need to perform some specific stuff during creation new object instance (only once and only during creation).

  3. When you need to perform all 5 steps which new keyword performs under the hood, and which simple function call won't perform.

cn007b
  • 16,596
  • 7
  • 59
  • 74
1

ES6 classes are in fact special functions.

Classes require the use of the new operator to create a new instance, as such invoking a class without the new operator results in an error, as it's required for the class constructor to create a new instance.

Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35