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. Its like you read my mind! You appear to know a lot about this, like you wrote the book
    in it or something. I think that you can do with some
    pics to drive the message home a little bit, but instead of that, this is great
    blog. A fantastic read. I will definitely be back.

    Also visit my homepage :: Lotto VIP thailand

  2. Hi outstanding blog! Does running a blog like this take a great deal of work?
    I have no understanding of coding however I had been hoping to start
    my own blog in the near future. Anyhow, if you have any ideas or tips for
    new blog owners please share. I know this is off topic but I just had
    to ask. Appreciate it!

  3. Với chế độ chăm sóc khách hàng tận tình, tôi cảm thấy mình được xem trọng hơn bao giờ hết!! # # anyKeyWord## 789bet