Example 1 — Require new
Common guard pattern.
JavaScript
function Point(x) {
if (!new.target) throw new TypeError("Call with new");
this.x = x;
}
console.log(new Point(1).x);How It Works
- Guard ensures constructor use.
Inside a function or constructor, new.target is the constructor invoked by new. If the function was called without new, new.target is undefined.
function F() {
console.log(new.target === F);
}
new F();
F();Common guard pattern.
function Point(x) {
if (!new.target) throw new TypeError("Call with new");
this.x = x;
}
console.log(new Point(1).x);new.target is the derived class.
class A {
constructor() { console.log(new.target.name); }
}
class B extends A {}
new B();Creating instances.
console.log(new String("x").valueOf());CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful