Javascript, instantiate without new

23-01-2018 • Javascript Patterns

Since constructors in javascript are just functions it is very easy to forget the new keyword. Also sometimes it can be quite handy not to have to type the new keyword all the time.

function MyClass(args) {
  if (!(this instanceof MyClass)) return new MyClass(args)

  this.args = args
}

const myObject = MyClass('some text')

console.log(myObject instanceof MyClass) // true

All the magic happens in the following line:

if (!(this instanceof MyClass)) return new MyClass(args)

If we call the function without the new keyword it is not an instance of MyClass and therefore it will instantiate a new instance and return it.