Why can classes not be called without 'new', unlike regular functions?
Short answer
Class constructors are designed to enforce proper object construction; calling a class without new throws a TypeError by specification, unlike ordinary functions which silently run with 'this' bound to undefined (in strict mode) or the global object.
Advertisement
AModel answer
Class constructors are designed to enforce proper object construction; calling a class without new throws a TypeError by specification, unlike ordinary functions which silently run with 'this' bound to undefined (in strict mode) or the global object.
class Foo {}
Foo(); // TypeError: Class constructor Foo cannot be invoked without 'new'Real-world example
Preventing a common bug where a class is accidentally called like a plain function and silently misbehaves.
Likely follow-ups
- How do factory functions differ from classes in this respect?
Related topics