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. Great blog you’ve got here.. It’s difficult to find high-quality writing like yours
    these days. I honestly appreciate individuals like you!
    Take care!!

  2. Hello there, You have done a great job. I will definitely
    digg it and personally suggest to my friends. I am sure they will be benefited
    from this website.

  3. Magnificent web site. Lots of helpful information here.

    I’m sending it to several friends ans additionally sharing in delicious.
    And certainly, thanks in your effort!

  4. Whoa! This blog looks just like my old one! It’s on a totally
    different topic but it has pretty much the same page layout and design. Superb choice of colors!

  5. Excellent site you have here but I was wondering if you knew of any forums that cover the same
    topics discussed in this article? I’d really love to be a part of
    community where I can get feed-back from other experienced people that share the same interest.
    If you have any recommendations, please let me
    know. Thank you!

  6. I have learn some excellent stuff here. Definitely worth bookmarking for revisiting.
    I wonder how a lot attempt you put to create one of these wonderful informative website.