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. Публикация предлагает читателю не просто информацию, а инструменты для анализа и саморазвития. Мы стимулируем критическое мышление, предлагая различные точки зрения и призывая к самостоятельному поиску решений.
    Перейти к полной версии – https://www.arctichydro.is/hiring-a-qualified-plumber-5

  2. We stumbled over here coming from a different website and thought I should check things out.
    I like what I see so now i am following you. Look forward to looking into your web page repeatedly.

  3. naturally like your web site however you need to take
    a look at the spelling on several of your posts.

    Several of them are rife with spelling issues and I in finding it very troublesome to inform the
    truth however I’ll surely come again again.

  4. Thank you for sharing your thoughts. I really appreciate your efforts and I am waiting for your further write ups thank you once
    again.

  5. Hey there, You’ve done a great job. I will definitely
    digg it and personally suggest to my friends. I am sure they’ll be benefited
    from this web site.