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. Greetings! This is my first visit to your blog!
    We are a team of volunteers and starting a new initiative in a community
    in the same niche. Your blog provided us useful information to work on. You have done a marvellous job!

  2. Hello there! I could have sworn I’ve visited this blog before but after going through a few of the
    posts I realized it’s new to me. Regardless, I’m certainly happy I found it and I’ll be book-marking it and checking back frequently!

  3. I’m gone to say to my little brother, that he should also go to see this
    webpage on regular basis to obtain updated from hottest news update.

  4. Hello, Neat post. There is a problem along with your web site in internet explorer,
    could check this? IE still is the market chief and a big component to people will miss your excellent writing because of this problem.