CoffeeScript lazy singleton class instance function

Explanation

“@instance:” allows us to attach an object/value to the Foo class instead of Foo’s prototype. Recall that “@” in CoffeeScript refers to JavaScript’s “this”.

After “@instance:” there is a function that is immediately executed. This function returns a function, closed around a variable called instance. Both these functions have their context (their “this”) bound to the Foo object using CoffeeScript’s wonderful “define and bind” operator “=>” as opposed to the normal function definition operator “->”.

When called, the function that “@instance” ends up referring to simply checks to see if the “instance” variable is empty and if so, assigns a new instance of Foo to it. Newing up a Foo is done using the “@” symbol since the function’s “this” refers to the Foo object. It then returns the instance.

Output

The CoffeeScript above compiles down to this:

23,235 thoughts on “CoffeeScript lazy singleton class instance function

  1. Hello! This is my first comment here so I just wanted to give a quick shout out and say I really enjoy reading through your blog posts.
    Can you recommend any other blogs/websites/forums that deal with the
    same topics? Thanks for your time!

    Also visit my web page: index

  2. Hi to every body, it’s my first pay a visit of this blog; this
    weblog carries awesome and genuinely fine information designed for readers.

  3. Hey! I realize this is sort of off-topic but I needed to ask.
    Does operating a well-established blog such as yours take a large amount of
    work? I’m brand new to writing a blog however I do write in my journal daily.
    I’d like to start a blog so I can share my personal experience and thoughts online.
    Please let me know if you have any kind of recommendations or tips for new aspiring blog owners.

    Thankyou!

  4. My partner and I absolutely love your blog and find most of your post’s to be what precisely I’m looking for.
    can you offer guest writers to write content
    in your case? I wouldn’t mind creating a post or elaborating on a few of the subjects you write
    regarding here. Again, awesome website!

  5. Hi! I could have sworn I’ve visited your blog before but after browsing through some
    of the articles I realized it’s new to me.
    Nonetheless, I’m definitely delighted I came across it and I’ll
    be bookmarking it and checking back often!

  6. I am truly thankful to the owner of this web page who has shared this great paragraph at at this place.

  7. Excellent site you have here.. It’s hard to find quality writing like yours nowadays.

    I seriously appreciate individuals like you!
    Take care!!

  8. If you want to increase your know-how simply keep visiting this web
    site and be updated with the most recent news posted here.