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. Wonderful blog! I found it while browsing on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News?

    I’ve been trying for a while but I never seem to get there!
    Appreciate it

  2. Attractive section of content. I just stumbled upon your site and in accession capital to assert that I acquire actually enjoyed account your blog posts.
    Any way I’ll be subscribing to your augment and even I achievement
    you access consistently rapidly.

  3. Hi mates, how is everything, and what you want to say concerning this article, in my view its in fact amazing in favor
    of me.

  4. Incredible! This blog looks just like my old one! It’s on a entirely different subject but it has pretty much the same page
    layout and design. Great choice of colors!

  5. Currently it seems like Movable Type is the preferred blogging
    platform available right now. (from what I’ve read) Is that what you’re using
    on your blog?

  6. Wow, incredible blog format! How lengthy have you been running a blog for?
    you make blogging glance easy. The total look
    of your website is great, as well as the content material!

  7. Do you have a spam problem on this website; I also am a blogger, and I was curious about your situation; we have created some nice methods
    and we are looking to trade strategies with others, why not shoot me an e-mail if interested.

  8. I’ve been browsing on-line greater than three hours nowadays, but I never discovered any interesting article like yours.

    It is beautiful worth sufficient for me. In my opinion, if all web owners and bloggers made excellent content material as you did, the internet
    will likely be much more helpful than ever before.