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. Admiring the persistence you put into your site and in depth information you
    offer. It’s great to come across a blog every
    once in a while that isn’t the same unwanted rehashed information. Great read!

    I’ve bookmarked your site and I’m including your RSS feeds to my Google
    account.

  2. Thanks for your personal marvelous posting! I genuinely enjoyed
    reading it, you happen to be a great author.I will make sure to bookmark your blog and may come back from now on. I want to encourage
    you to continue your great job, have a nice morning!

  3. Hello there, I discovered your site by way of Google at the same time as searching for
    a comparable matter, your site came up, it appears to be like
    good. I’ve bookmarked it in my google bookmarks.
    Hi there, simply become alert to your blog via Google, and found that it’s really informative.
    I’m gonna watch out for brussels. I’ll be grateful in case you proceed this in future.
    Numerous other folks shall be benefited from your writing.

    Cheers!

  4. Hello! I’ve been following your site for a while
    now and finally got the bravery to go ahead
    and give you a shout out from Humble Tx! Just wanted to mention keep up the fantastic job!

  5. Magnificent beat ! I would like to apprentice at the same time as you amend your website, how could i subscribe for a weblog
    site? The account helped me a acceptable deal. I had been tiny bit familiar of this your broadcast provided brilliant transparent idea

  6. Wow, incredible blog layout! How long have you been blogging
    for? you made blogging look easy. The overall look of your web site is wonderful, let alone the content!

  7. I will immediately grasp your rss feed as I can’t to
    find your email subscription hyperlink or e-newsletter service.
    Do you’ve any? Kindly let me recognize so that I could
    subscribe. Thanks.