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 have to thank you for the efforts you’ve put in writing
    this blog. I really hope to check out the same high-grade content by you later on as well.
    In fact, your creative writing abilities has inspired me to get my own site now ;)

  2. That is very attention-grabbing, You are an excessively skilled blogger.
    I have joined your rss feed and sit up for looking for extra
    of your excellent post. Also, I have shared your site in my social networks

  3. Thank you, I have recently been looking for info about this
    subject for a while and yours is the best I have found
    out till now. However, what in regards to the conclusion? Are you sure concerning the supply?

  4. I do not even know how I ended up here, but I thought this post was great.

    I don’t know who you are but definitely you’re going to a famous blogger if you aren’t already ;) Cheers!

  5. It’s the best time to make some plans for the longer term and it is time to be happy.

    I have read this post and if I could I desire to suggest you few attention-grabbing issues or tips.
    Perhaps you could write subsequent articles regarding this article.

    I want to read even more things approximately it!

  6. Hello, 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 protect against it, any plugin or anything you can advise?
    I get so much lately it’s driving me mad so any
    help is very much appreciated.