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. What i don’t realize is actually how you’re not actually much more neatly-appreciated than you may be
    right now. You’re so intelligent. You understand therefore significantly in the case of this topic, produced me in my view consider it
    from so many numerous angles. Its like women and men aren’t fascinated until it
    is something to do with Woman gaga! Your own stuffs outstanding.
    Always take care of it up!

  2. Great blog! Is your theme custom made or did you download
    it from somewhere? A design like yours with a few simple tweeks would really make my blog jump out.

    Please let me know where you got your theme.
    Cheers

  3. It’s amazing to pay a visit this web page and reading the
    views of all friends concerning this piece of writing, while I am also keen of getting know-how.

  4. Сравните цены на ноутбуки https://n-katalog.ru/category/noutbuki/list в десятках магазинов: для работы учебы и игр. Характеристики отзывы фото бенчмарки. Фильтры по процессору ОЗУ SSD диагонали видео весу и автономности. Следите за акциями и динамикой стоимости — выбирайте выгодное предложение с доставкой.