Skip to content

Instantly share code, notes, and snippets.

@MoOx
Last active August 29, 2015 14:04
Show Gist options
  • Save MoOx/b2551b4b404d4d4bee6b to your computer and use it in GitHub Desktop.
Save MoOx/b2551b4b404d4d4bee6b to your computer and use it in GitHub Desktop.
Constructor pattern to allow both new and functional usage
function Ctor(options) {
if(!(this instanceof Ctor)) { // same as (!Ctor.prototype.isPrototypeOf(this))
return Ctor.apply(Object.create(Ctor.prototype), arguments)
}
// ...
return this
}
var Ctor = require("ctor")
var instance = new Ctor({/*...*/})
var ctor = require("ctor")
var instance = ctor({/*...*/})
@bloodyowl
Copy link

function Ctor(param1, param2){
  if(!Ctor.prototype.isPrototypeOf(this)) {
    return Ctor.apply(
      Object.create(Ctor.prototype),
      arguments // needed if more than one param
    )
  }
  // code
  return this // imperative when `new` isn't called, as there is no default `returnValue`
}

@MoOx
Copy link
Author

MoOx commented Aug 6, 2014

Updated according to your comment.
Thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment