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:

15,664 thoughts on “CoffeeScript lazy singleton class instance function

  1. Solid breakdown of on-page strategies. I’ve seen big wins by auditing title tags and internal links— SEO Company helped me map priorities and execute fast.

  2. It’s the best time to make some plans for the future and it’s time to be
    happy. I’ve read this post and if I could I wish to suggest you few
    interesting things or advice. Maybe you can write next articles referring to this article.
    I wish to read even more things about it!

  3. Wow that was strange. I just wrote an extremely long comment but
    after I clicked submit my comment didn’t show up. Grrrr…
    well I’m not writing all that over again. Anyhow, just wanted
    to say superb blog!

  4. Hello! I know this is kinda off topic however , I’d figured
    I’d ask. Would you be interested in trading links or maybe guest
    authoring a blog article or vice-versa? My site goes over a lot of the same topics as yours and I feel we could greatly
    benefit from each other. If you are interested feel free to send me an e-mail.
    I look forward to hearing from you! Terrific blog by the way!

  5. I like the valuable information you supply to your articles.
    I’ll bookmark your blog and test once more right here frequently.
    I am somewhat sure I’ll be told plenty of new stuff right here!
    Good luck for the next!

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>