JavaScriptFundamental (ES6), part 1
Use new.target to require new in JavaScript
49 new.target, and refusing to run without new
fairWrite a constructor function that notices it was called without new and fixes it up. Then write an abstract base class whose constructor throws when it is the direct target, and prove a subclass passes straight through it.
Stuck? Three hints, smallest first
- 1.
new.targetis the constructor thatnewwas applied to, orundefinedin a plain call. - 2. In a base constructor reached through
super(),new.targetis the subclass. - 3. A class constructor cannot be called without
newat all, so the fix-up trick only applies to plain functions.
const seen = [];
function Fee(kobo) {
seen.push(new.target === undefined ? 'no new' : new.target.name);
if (!new.target) return new Fee(kobo); // called flat: put it right
this.kobo = kobo;
}
class Levy {
constructor(kobo) { this.kobo = kobo; }
}
class Payment {
static built = [];
constructor(kobo) {
if (new.target === Payment) throw new TypeError('Payment is abstract');
Payment.built.push(new.target.name);
this.kobo = kobo;
}
}
class Transfer extends Payment {}
const attempt = (fn) => { try { return fn(); } catch (e) { return e.constructor.name; } };
const withNew = new Fee(500);
const withoutNew = Fee(500);
const calledFlat = attempt(() => Levy(500));
const abstractDirect = attempt(() => new Payment(100));
const transfer = new Transfer(750);
console.log('new.target seen :', seen);
console.log('with new :', withNew, '| without new:', withoutNew);
console.log('class called flat:', calledFlat);
console.log('new Payment() :', abstractDirect, '| new Transfer():', transfer);
console.log('base saw target :', Payment.built);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('with new, new.target is the function itself; without it, undefined', seen, ['Fee', 'no new', 'Fee']);
test('the fix-up call still produced a real instance', [withoutNew instanceof Fee, withoutNew.kobo], [true, 500]);
test('and it has the same own keys as the proper call', [Object.keys(withoutNew), Object.keys(withNew)], [['kobo'], ['kobo']]);
test('a class constructor refuses a call without new outright', calledFlat, 'TypeError');
test('an abstract base refuses to be the direct target', abstractDirect, 'TypeError');
test('but a subclass passes through it', transfer.kobo, 750);
test('and the base can see which subclass is being built', Payment.built, ['Transfer']);
test('the subclass instance is both classes', [transfer instanceof Transfer, transfer instanceof Payment], [true, true]);
The first assertion is the whole mechanism: seen reads ['Fee', 'no new', 'Fee'] because the flat call recorded 'no new' and then recursed with new, recording 'Fee' again. Before new.target the idiom was if (!(this instanceof Fee)), which is wrong in strict mode where this is undefined and reading it throws.
The abstract-base pattern is the useful half. new.target === Payment is true only when someone instantiated the base directly; through super() it is the subclass, which is also how a base constructor can log or register what is being built. Note that classes need no new.target guard against flat calls — the language already throws — so new.target in a class body is about the abstract check and about telling subclass from base.