How to use new.target to detect whether a function was called using the new operator in JavaScript

2 Answers

0 votes
function f() {
  if (!new.target) { throw 'f() called without new'; }

  console.log('f() called without new')
}

try {
  f();
} catch (e) {
  console.log(e);
}



/*
run:

f() called without new

*/

 



answered Nov 19, 2020 by avibootz
0 votes
function f() {
  if (!new.target) { throw 'f() called without new'; }

  console.log('f() called with new')
}

let o = new f();




/*
run:

f() called with new

*/

 



answered Nov 19, 2020 by avibootz
...