Skip to content

Instantly share code, notes, and snippets.

@wenzowski
Last active August 29, 2015 14:10
Show Gist options
  • Save wenzowski/f40a894402017c644ee1 to your computer and use it in GitHub Desktop.
Save wenzowski/f40a894402017c644ee1 to your computer and use it in GitHub Desktop.
module pattern with require
function construct(ctor) {
function P(args) { return ctor.apply(this, args) }
P.prototype = ctor.prototype
return function create(args) {
return new P(args)
}
}
module.exports = ExampleProto
function ExampleProto() {
if (!(this instanceof ExampleProto)) return ExampleProto.prototype.create(arguments)
this.arguments = Array.prototype.slice.call(arguments)
}
ExampleProto.prototype.create = construct(ExampleProto)
ExampleProto.prototype.pub = function () {
return 'public'
}
function priv() {
return 'private'
}
ExampleProto.prototype.callPriv = function () {
return priv()
}
var ExampleProto = require('./ExampleProto')
console.log('can be called with new:', (new ExampleProto) instanceof ExampleProto)
console.log('can be called as a function:', ExampleProto() instanceof ExampleProto)
var ExampleProto = (function () {
function construct(ctor) {
function P(args) { return ctor.apply(this, args) }
P.prototype = ctor.prototype
return function create(args) {
return new P(args)
}
}
function ExampleProto() {
if (!(this instanceof ExampleProto)) return ExampleProto.prototype.create(arguments)
this.arguments = Array.prototype.slice.call(arguments)
}
ExampleProto.prototype.create = construct(ExampleProto)
ExampleProto.prototype.pub = function () {
return 'public'
}
function priv() {
return 'private'
}
ExampleProto.prototype.callPriv = function () {
return priv()
}
return ExampleProto
})()
console.log('can be called with new:', (new ExampleProto) instanceof ExampleProto)
console.log('can be called as a function:', ExampleProto() instanceof ExampleProto)
class ExampleProto
construct = (ctor) ->
P = (args) ->
ctor.apply @, args
P:: = ctor::
create = (args) ->
new P(args)
create: construct(ExampleProto)
constructor: (args...) ->
return ExampleProto::create(args) unless @ instanceof ExampleProto
@arguments = args
priv = ->
"private"
pub: ->
"public"
callPriv: ->
priv()
console.log 'can be called with new:', (new ExampleProto) instanceof ExampleProto
console.log 'can be called as a function:', ExampleProto() instanceof ExampleProto
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment