Constructor-mode detection
Detect whether a function is being used as a constructor.
JS Puzzles · Const
new.target reveals whether the current function was called with new. It is undefined for regular calls and refers to the function during construction.
new.target is a special expression available inside function and class bodies. It is undefined for an ordinary call and identifies the constructor used for construction, allowing code to distinguish constructor mode from regular invocation.
new.targetThe expression evaluates to undefined for regular calls, or to the constructor function when called with new.
new.target to tell whether a function was invoked as a constructor.undefined, while construction produces the called function.new.target is undefined; do not treat it as a normal object property.new.target outside a function or class body causes a syntax error.function User(name) {
if (!new.target) return new User(name);
this.name = name;
}
console.log(new User("Ada").name);The function creates an instance whether it is called directly or with new.
Detect whether a function is being used as a constructor.
Make a constructor function work with or without explicitly writing new.
Reject or handle accidental regular invocation of constructor-style functions.
newconstructor