new.target Guards Missing new And Abstract Bases
Plain function calls leave new.target undefined, so constructors can throw a clear error, and the same check lets base classes reject direct instantiation.
Code
// Function constructors: detect a missing "new"
function Bag(items) {
if (!new.target) {
throw new TypeError("Bag() requires new");
}
this.items = items;
}
try {
Bag(["x"]);
} catch (error) {
console.log("plain call:", error.message);
}
const bag = new Bag(["x"]);
console.log("bag ok:", bag.items.length === 1);
// Abstract base class: reject direct instantiation, allow subclasses
class Store {
constructor() {
if (new.target === Store) {
throw new TypeError("Store is abstract");
}
}
}
class MemoryStore extends Store {}
try {
new Store();
} catch (error) {
console.log("abstract:", error.message);
}
console.log("subclass ok:", new MemoryStore() instanceof MemoryStore);Output
Captured from a sandboxed run of this snippet in the build pipeline.
plain call: Bag() requires new
bag ok: true
abstract: Store is abstract
subclass ok: trueWhat the code sets in motion
new.target Guards Missing new And Abstract Bases comes down to the classes Store, MemoryStore and ok and the function Bag.
The failure path is explicit — TypeError is raised when the guard condition holds.
Points of care
- Nothing to vet in a supply-chain review — the file pulls in no packages.
- The guard
!new.targetjumps straight out of the flow with an earlythrowwhen its condition holds.
Using it
The entry-point signature is function Bag(items)
The file’s steps show up in the output as plain call:, bag ok:, abstract:.
Key statements
throw new TypeError("Bag() requires new");
throw new TypeError("Store is abstract");
Interactive Tools for This Topic
FAQ
- Is there a failure path for bad input?
- The code refuses to continue: `TypeError` is thrown while the state is still recoverable.
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. The file defines `Bag` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.