🔸new.target
in normal function calls, new.target is undefined.
function User(name) {
// ⭐️ if called normally, add `new`.
if (!new.target) { return new User(name); }
this.name = name;
}
let joe = User('Joe'); // ⭐️ `new` not required nowin class constructors (or function called using new), new.target refers to the constructor/function that was directly invoked by new. for example:
new A(); // new.target === A
new B(); // new.target === B⚠️ class constructors cannot be invoked without 'new'.
new.target "pseudo-property" is available in all functions.
💾 replit:new.target
// ----------------------------------------------------
// in class constructors, `new.target` refers to
// the constructor that was directly invoked by `new`.
// for example:
// new A(); // new.target === A
// new B(); // new.target === B
// ----------------------------------------------------
class A {
constructor() {
console.log(`new ${new.target.name}(): new.target === A ? ${new.target === A}`);
}
}
class B extends A {
constructor() {
super();
}
}
const a = new A(); // new.target === A ? true
const b = new B(); // new.target === A ? false
// A();
// ⛔️ TypeError: Class constructor `A` cannot be invoked without 'new'
// ----------------------------------------------------
// in normal function calls, `new.target` is `undefined`.
// ----------------------------------------------------
function User(name) {
// ⭐ if called without `new`, add `new` automatically.
if (!new.target) { return new User(name) }
this.name = name;
}
let joe = User('Joe'); // ⭐ `new` not required now
console.log(joe.name); // 'Joe'new.target - detect whether a function/constructor was called using new.
Last updated
Was this helpful?