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. Do you have a spam problem on this website;
    I also am a blogger, and I was wanting to know your situation; we have developed some nice methods and we are looking to trade strategies with other folks, be sure to shoot me an e-mail
    if interested.

  2. I seriously love your website.. Excellent colors & theme.
    Did you develop this amazing site yourself? Please reply back as
    I’m hoping to create my own site and want to learn where you got this from or exactly what the theme
    is named. Thanks!

  3. Khi thấy quảng cáo cờ bạc nhảy pop-up, đừng bấm tắt vội, hãy đóng tab và quét lại trình duyệt. Hướng dẫn từng bước có ở ma túy .

  4. Great blog here! Also your web site 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 quickly as
    yours lol

  5. I really like your blog.. very nice colors & theme. Did you make this
    website yourself or did you hire someone to do it for you?
    Plz answer back as I’m looking to create my own blog and would like to know where u got this from.

    kudos

  6. Hi there to all, it’s actually a good for me to go
    to see this website, it includes helpful Information.

    Take a look at my web site 밤알바