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. Hey There. I found your blog the usage of msn. That is an extremely well
    written article. I will be sure to bookmark it and come back to learn extra of
    your helpful information. Thank you for the post.
    I’ll certainly return.

  2. This paragraph gives clear idea for the new users of blogging, that in fact how to
    do blogging.

  3. I’m not sure where you are getting your information, but good topic.
    I needs to spend some time learning much more or understanding more.
    Thanks for excellent info I was looking for this info for my mission.

  4. These are actually enormous ideas in about blogging. You have touched
    some pleasant factors here. Any way keep up wrinting.

  5. Hi there are using WordPress for your blog
    platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you need any coding knowledge to make your own blog?

    Any help would be greatly appreciated!

  6. QRIS108 merupakan situs game online resmi terbaik di Indonesia yang menyediakan berbagai permainan mudah
    dimainkan dengan bonus hingga promo menarik setiap hari

  7. I blog frequently and I really appreciate your information. Your article
    has really peaked my interest. I will bookmark your site
    and keep checking for new information about once a week.
    I opted in for your Feed too.

  8. Yesterday, while I was at work, my cousin stole my iPad and
    tested to see if it can survive a 25 foot drop, just so she can be a youtube
    sensation. My apple ipad is now destroyed and she has 83 views.
    I know this is totally off topic but I had to share it with someone!

  9. Hi there mates, good article and fastidious urging commented at
    this place, I am genuinely enjoying by these.