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. В этом тексте собрано множество случайных сведений и довольно неопределённых мыслей, которые могут чем-то заинтересовать. Мы отмечаем моменты, которые не особенно важны, но всё же занимают своё место в повествовании.
    Вот – dogging

  2. I know this if off topic but I’m looking into starting my own weblog and was curious what all is required to get setup?

    I’m assuming having a blog like yours would cost a pretty penny?

    I’m not very web savvy so I’m not 100% sure. Any suggestions or
    advice would be greatly appreciated. Many thanks

  3. Love seeing before-and-after roof projects. Quality flashing and proper drip edge make all the difference. Thinking of booking with near me for our eavestrough replacement.

  4. Useful info. Lucky me I discovered your web site accidentally,
    and I’m shocked why this coincidence did not took place earlier!
    I bookmarked it.