Skip to content

Instantly share code, notes, and snippets.

@meltingice
Last active December 10, 2015 01:09
Show Gist options
  • Save meltingice/4356210 to your computer and use it in GitHub Desktop.
Save meltingice/4356210 to your computer and use it in GitHub Desktop.
This is a nice way to force instantiation in a Coffeescript "class". It basically allows it to look like a function. Adapted from John Resig's blog post http://ejohn.org/blog/simple-class-instantiation/
class Foo
constructor: ->
return new Foo() unless @ instanceof Foo
# Guaranteed to be an object here
@announce()
announce: -> console.log "here!"
# These are equivalent now
Foo()
new Foo()
# If you want to apply the arguments to the instantiated object,
# you have to do something like this.
class Foo
constructor: ->
if @ instanceof Foo
console.log arguments
else
FooInstance = ->
FooInstance:: = Foo::
instance = new FooInstance()
obj = Foo.apply(instance, Array.prototype.slice.apply(arguments))
return if Object(obj) is obj then obj else instance
# These are the same
Foo(1, 2, 3)
new Foo(1, 2, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment