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 like the helpful info you provide to your articles. I will
    bookmark your blog and test again right here frequently.
    I am slightly sure I’ll learn plenty of new stuff proper right here!
    Best of luck for the next!

    Feel free to surf to my web page; furnace repair

  2. Hi there, I found your website by way of Google while
    looking for a comparable subject, your website got here up, it seems to be good.

    I have bookmarked it in my google bookmarks.
    Hi there, simply was alert to your weblog via Google, and found that it is
    truly informative. I’m gonna be careful for brussels.
    I’ll be grateful in case you continue this in future.
    Many other people can be benefited from your writing. Cheers!