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. Outstanding post however I was wanting to know if you could write a litte more on this
    subject? I’d be very grateful if you could elaborate a little bit more.
    Many thanks!

  2. Nice blog here! Also your website loads up fast!
    What host are you using? Can I get your affiliate link to your host?
    I wish my web site loaded up as fast as yours lol

  3. Can I just say what a comfort to find somebody
    that genuinely understands what they’re talking about on the internet.
    You certainly know how to bring an issue to light and make it important.
    More and more people must look at this and understand this side of the story.
    I can’t believe you are not more popular because you surely have
    the gift.

  4. ข้อมูลชุดนี้ ให้ข้อมูลดี ค่ะ

    ผม เคยเห็นเนื้อหาในแนวเดียวกันเกี่ยวกับ มุมมองที่คล้ายกัน
    ซึ่งอยู่ที่ Owen
    เหมาะกับคนที่สนใจเรื่องนี้

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

    จะรอติดตามเนื้อหาใหม่ๆ ต่อไป

  5. Terrific article! This is the kind of info that should be shared across the net.
    Disgrace on the search engines for not positioning this post higher!

    Come on over and consult with my website . Thanks =)

  6. Excellent article. Keep writing such kind of information on your page.
    Im really impressed by it.
    Hello there, You have done a fantastic job. I’ll certainly diigg it and iin myy view sugggest to my friends.
    I’m sure they will be benefited fro this website.

  7. I am not sure where you’re getting your information, but good topic.
    I needs to spend some time learning much more or understanding more.
    Thanks for wonderful information I was looking for this info for
    my mission.