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. Quick reference on adu builders. It outlines the basics without fluff. Useful for planning your next steps.

  2. That is really attention-grabbing, You’re an overly skilled blogger.
    I’ve joined your feed and stay up for in quest of extra of your magnificent post.
    Additionally, I have shared your website in my social networks

  3. This post is actually a pleasant one it assists new internet people, who are wishing in favor of blogging.

  4. เนื้อหานี้ มีประโยชน์มาก ค่ะ
    ดิฉัน ได้อ่านบทความที่เกี่ยวข้องกับ ข้อมูลเพิ่มเติม

    ดูต่อได้ที่ Franklin
    น่าจะถูกใจใครหลายคน

    มีการยกตัวอย่างที่เข้าใจง่าย
    ขอบคุณที่แชร์ เนื้อหาดีๆ นี้
    จะรอติดตามเนื้อหาใหม่ๆ ต่อไป

  5. Hello! I could have sworn I’ve visited this web site before
    but after looking at a few of the posts I realized it’s new
    to me. Anyhow, I’m certainly delighted I stumbled upon it and I’ll be bookmarking it and checking back regularly!

  6. Hello all, here every person is sharing these know-how, therefore it’s
    fastidious to read this blog, and I used to go to see this webpage every day.

  7. With havin so much content do you ever run into any issues
    of plagorism or copyright infringement? My blog
    has a lot of completely unique content I’ve either created myself or outsourced but it seems a lot of it is popping it up all over
    the internet without my authorization. Do you know any solutions to help stop
    content from being stolen? I’d truly appreciate it.