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. I really like what you guys are usually up too. This kind of clever work and coverage!
    Keep up the terrific works guys I’ve you guys to blogroll.

  2. Hey there! Quick question that’s completely off topic.
    Do you know how to make your site mobile friendly?
    My site looks weird when browsing from my iphone.
    I’m trying to find a theme or plugin that might be able to fix this issue.
    If you have any suggestions, please share. Appreciate it!

  3. Good day! Do you know if they make any plugins to help with SEO?

    I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains.

    If you know of any please share. Thanks!

  4. Have you ever considered about adding a little bit more than just your articles?

    I mean, what you say is important and all. Nevertheless think of
    if you added some great graphics or videos to give your posts more, “pop”!
    Your content is excellent but with pics and videos, this site could
    undeniably be one of the very best in its niche. Superb blog!

  5. Thank you for the good writeup. It in reality used to be a amusement
    account it. Look complex to far added agreeable from you!
    By the way, how can we be in contact?

  6. Hello, this weekend is pleasant designed for me, because this point in time i am reading this impressive educational article here at
    my house.

  7. Hi! Someone in my Facebook group shared this site with
    us so I came to take a look. I’m definitely loving the information. I’m bookmarking and will be tweeting this
    to my followers! Excellent blog and outstanding style and design.

  8. Hello! I could have sworn I’ve been to this blog before but after browsing through many of the
    posts I realized it’s new to me. Anyhow, I’m definitely happy I
    discovered it and I’ll be bookmarking it and checking back
    often!