JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 721
  • Score
    100M100P100Q100100F
  • License MIT

Make the 'new' keyword optional for ES6 classes

Package Exports

  • old

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (old) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

no-new

npm version

Make the 'new' keyword optional for ES6 classes

no-new

Usage

npm install no-new

var nonew = require('no-new')

class Class {
  // ...
}

var Class2 = nonew(Class)

Class() // throws error
Class2() // creates an instance of Class

Rationale

With ES5 "constructor" functions, a common pattern is to make the new keyword optional by doing something like the following:

function Foo () {
  if (!(this instanceof Foo)) return new Foo()
  // do constructor stuff
}

Recently, ES6 introduced classes to replace constructor functions. However, if these classes are instantiated without new, an error is thrown: TypeError: Class constructor Foo cannot be invoked without 'new'. This module makes new optional, even for these ES6 classes.

Credit

Thank you to Sorella in ##javascript (Freenode) for the clean solution.