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. My partner and I stumbled over here by a different web address and thought I should check things out.
    I like what I see so now i am following you. Look forward to
    looking at your web page for a second time.

  2. Your mode of describing the whole thing in this
    paragraph is really pleasant, all can easily be
    aware of it, Thanks a lot.

  3. Sweet blog! I found it while searching on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem
    to get there! Thanks

  4. Hi to every body, it’s my first visit of this blog;
    this web site includes remarkable and actually good stuff in support of visitors.

  5. Your method of explaining the whole thing in this piece of writing is truly good, every one be able to simply be aware of it, Thanks a lot.

  6. viralvideo
    funnyvideo
    funny
    funnyvideo
    funnyshorts
    funnyvideos
    nasa
    নাসাভাইবিনোদোন