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. After looking at a handful of the articles on your blog, I honestly like your technique
    of blogging. I added it to my bookmark webpage list and will be checking back in the near future.
    Take a look at my web site as well and let me know your opinion.

  2. I’m extremely impressed with your writing skills and also with the layout on your blog.
    Is this a paid theme or did you customize it yourself? Either way keep up the excellent quality
    writing, it is rare to see a great blog like this one nowadays.

  3. Hi, i read your blog from time to time and i own a similar one and i
    was just curious if you get a lot of spam comments?

    If so how do you reduce it, any plugin or anything you can suggest?
    I get so much lately it’s driving me insane
    so any assistance is very much appreciated.

  4. whoah this weblog is magnificent i love reading your articles.
    Stay up the good work! You realize, a lot of individuals are looking round for this info, you can aid them greatly.

  5. I got this website from my buddy who informed me on the topic of this website
    and at the moment this time I am visiting this website and reading
    very informative posts at this time.

  6. unblocked games

    Excellent article. Keep writing such kind of info on your
    page. Im really impressed by it.
    Hi there, You have performed an incredible job.

    I will certainly digg it and personally recommend to my
    friends. I’m confident they will be benefited from this website.