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:

21,964 thoughts on “CoffeeScript lazy singleton class instance function

  1. I visited various web sites but the audio feature for audio songs current at this site is
    truly superb.

  2. Этот обзор позволяет по-новому взглянуть на вещи, на которые обычно и так смотрят. Мы упоминаем факты, которые мало что меняют, и события, значение которых трудно определить, но они всё равно здесь.
    Вот – testicle

  3. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something.
    I think that you can do with some pics to drive the message home a little bit, but
    other than that, this is great blog. An excellent read.
    I’ll certainly be back.

  4. You have made some decent points there. I looked on the
    web for more info about the issue and found most individuals will go along with your views on this website.

  5. I must thank you for the efforts you have put in penning this site.

    I’m hoping to check out the same high-grade blog posts from you in the future as well.
    In truth, your creative writing abilities has
    encouraged me to get my own site now ;)

  6. I’m really impressed with your writing skills as well as
    with the layout on your blog. Is this a paid theme or did you customize it yourself?

    Anyway keep up the nice quality writing, it’s rare to see a great blog
    like this one these days.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>