@activeprospect/old

1.1.5 • Public • Published

old

npm version

Make the 'new' keyword optional for ES6 classes

Usage

npm install old

var old = require('old')

class Class {
  // ...
}

var Class2 = old(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
  • Thanks to slikts in ##javascript for the name idea

Package Sidebar

Install

npm i @activeprospect/old

Weekly Downloads

125

Version

1.1.5

License

MIT

Unpacked Size

5.26 kB

Total Files

4

Last publish

Collaborators

  • jevensen
  • daniel.gershin
  • celolb
  • rafael.uchoa
  • jarrodbmiller
  • terbepetra
  • matteo.pandolfi
  • ericyd_ap
  • ivisilva
  • henriquelaki
  • carlo.anselmi
  • stefano.santonocito
  • carlhannusch
  • robdll
  • jorgemarrufo
  • apshoebkhan
  • samullen-ap
  • dpjones09
  • josevsp
  • johnb2
  • rickymcmurtrey
  • jgrayson03
  • apadmin
  • alexkwolfe
  • kellym
  • cgrayson
  • steveodom
  • ap_luisferreira
  • alisimbanegavi
  • benjmartin
  • sammarten
  • gabriel.roldan.ap
  • stwf-ap