Support for new.target

The new.target meta-property is new syntax introduced in ES2015. When an instance of a constructor is created via new, the value of new.target is set to be a reference to the constructor function initially used to allocate the instance. If a function is called rather than constructed via new, new.target is set to undefined.

new.target comes in handy when Object.setPrototypeOf or proto needs to be set in a class constructor. One such use case is inheriting from Error in NodeJS v4 and higher.

Example

  1. class CustomError extends Error {
  2. constructor(message?: string) {
  3. super(message); // 'Error' breaks prototype chain here
  4. Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
  5. }
  6. }

This results in the generated JS

  1. var CustomError = (function (_super) {
  2. __extends(CustomError, _super);
  3. function CustomError() {
  4. var _newTarget = this.constructor;
  5. var _this = _super.apply(this, arguments); // 'Error' breaks prototype chain here
  6. _this.__proto__ = _newTarget.prototype; // restore prototype chain
  7. return _this;
  8. }
  9. return CustomError;
  10. })(Error);

new.target also comes in handy for writing constructable functions, for example:

  1. function f() {
  2. if (new.target) { /* called via 'new' */ }
  3. }

Which translates to:

  1. function f() {
  2. var _newTarget = this && this instanceof f ? this.constructor : void 0;
  3. if (_newTarget) { /* called via 'new' */ }
  4. }