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 just wanted to give you a quick heads up and let you know a few of the images aren’t loading correctly.
    I’m not sure why but I think its a linking issue.
    I’ve tried it in two different web browsers and both show the same outcome.

  2. Woah! I’m really enjoying the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s challenging
    to get that “perfect balance” between superb usability and visual appearance.
    I must say you have done a excellent job with this. Additionally, the blog loads super quick for me on Internet explorer.
    Superb Blog!

  3. Can I simply just say what a comfort to find an individual who really understands
    what they’re talking about on the web. You certainly realize how to bring a problem to light and make it important.
    More and more people need to look at this and understand this side of the story.
    I was surprised you are not more popular since you certainly possess the gift.

  4. Admiring the commitment you put into your site and detailed information you present.
    It’s awesome to come across a blog every once in a while that isn’t the same out of date rehashed
    material. Excellent read! I’ve saved your site and I’m adding your
    RSS feeds to my Google account.