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:

21,921 thoughts on “CoffeeScript lazy singleton class instance function

  1. It’s really very complex in this busy life to listen news on Television, thus I simply use internet for that reason, and take the newest
    information.

  2. Storm season check: inspect flashing around chimneys and skylights. I’m scheduling maintenance through diy to catch issues early.

  3. I every time emailed this website post page to all my associates,
    because if like to read it after that my friends will too.

    my web page :: 밤알바

  4. It’s difficult to find knowledgeable people about this topic, but you seem
    like you know what you’re talking about! Thanks

  5. tradition contracting does respectable paintings on my area

    tradition contracting eavestrough & roofing kitchner roofing
    kitchner roofing custom contracting eavestrough & roofing
    customized-contracting roofing kitchener

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>