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. magnificent post, very informative. I ponder why the other experts of this sector do not notice this.

    You should proceed your writing. I am confident, you have a huge readers’ base already!

  2. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment
    is added I get three emails with the same comment.
    Is there any way you can remove me from that service?
    Thank you!

    Also visit my web blog; 토토사이트

  3. Every weekend i used to pay a visit this site, for the reason that i wish for enjoyment, for the reason that this this web page conations
    really fastidious funny material too.

  4. Hi! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for
    some targeted keywords but I’m not seeing very good results.
    If you know of any please share. Kudos!

  5. Right now it looks like Drupal is the preferred blogging
    platform out there right now. (from what I’ve read) Is that what you are using on your blog?

  6. Superb site you have here but I was curious if you knew of
    any forums that cover the same topics discussed in this
    article? I’d really like to be a part of community where I can get advice from other experienced people that share the same interest.
    If you have any suggestions, please let me know. Cheers!

  7. What’s up friends, nice piece of writing and nice urging
    commented here, I am actually enjoying by these.

  8. Pretty section of content. I just stumbled upon your website and in accession capital to
    assert that I get in fact enjoyed account your blog posts.
    Anyway I’ll be subscribing to your feeds and even I achievement you access consistently rapidly.