Last active
December 10, 2015 01:09
-
-
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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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