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. Hi! Someone in my Myspace group shared this website with us so I came to give it a look.
    I’m definitely loving the information. I’m bookmarking and will
    be tweeting this to my followers! Outstanding blog and fantastic design and style.

  2. Hey there! I’ve been reading your web site for a
    while now and finally got the bravery to go ahead and give you
    a shout out from New Caney Texas! Just wanted to say keep up the fantastic
    work!

  3. I have been browsing on-line greater than three hours nowadays, but
    I by no means discovered any interesting article like yours.
    It is lovely price enough for me. Personally, if all website owners and bloggers made just right content
    as you probably did, the internet might be a lot more helpful than ever before.

  4. Wow, wonderful blog format! How long have you been running a blog for?
    you make blogging look easy. The overall look of your web site is excellent, as smartly as the content material!

  5. Wow, amazing blog layout! How lengthy have you
    been blogging for? you made blogging look easy. The full glance of
    your website is great, as well as the content!

  6. Thanks for the marvelous posting! I certainly enjoyed
    reading it, you are a great author. I will always bookmark your blog and will often come back down the
    road. I want to encourage you to ultimately continue your
    great work, have a nice morning!