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 put up, very informative. I ponder why the other experts of this sector
    don’t realize this. You must proceed your writing. I am confident, you’ve a
    huge readers’ base already!

  2. Have you ever thought about publishing an e-book or guest authoring on other websites?
    I have a blog centered on the same information you discuss and would love to have you share some stories/information. I know my
    viewers would enjoy your work. If you’re even remotely interested, feel free to send me an e-mail.

  3. We stumbled over here by a different web page and
    thought I may as well check things out. I like what I see so now i’m following you.
    Look forward to exploring your web page yet again.

  4. Hello would you mind letting me know which webhost you’re utilizing?
    I’ve loaded your blog in 3 completely different internet browsers and I must say this blog
    loads a lot quicker then most. Can you recommend a good
    web hosting provider at a fair price? Cheers, I appreciate
    it!

  5. There’s definately a great deal to find out about this
    issue. I like all of the points you have made.

  6. You ought to take part in a contest for one of the
    most useful sites on the web. I most certainly will recommend this blog!