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. I must thank you for the efforts you’ve put in writing this site.
    I’m hoping to see the same high-grade blog posts by
    you in the future as well. In truth, your creative writing abilities has encouraged me to get my own, personal website now ;)

  2. Hello! This is my 1st comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading through your articles.
    Can you recommend any other blogs/websites/forums that deal
    with the same subjects? Thanks!

  3. Appreciating the persistence you put into your site and in depth information you offer.
    It’s good to come across a blog every once in a while that isn’t the
    same outdated rehashed material. Wonderful read!
    I’ve bookmarked your site and I’m including your RSS feeds to my Google account.

  4. Hey! I could have sworn I’ve been to this website
    before but after reading through some of the post I realized it’s new to me.

    Nonetheless, I’m definitely happy I found it
    and I’ll be bookmarking and checking back frequently!

  5. An interesting discussion is definitely worth comment.

    There’s no doubt that that you need to write more on this subject, it might not be a taboo
    matter but generally folks don’t talk about
    these topics. To the next! Best wishes!!