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. When Joe Biden was 10, his household moved to a suburb of Wilmington, Delaware, the place he attended Archmere, a personal Catholic
    college. He was followed by Robert Hunter in 1970 and Naomi in 1971.

  2. 신용카드현금화 – 급전이 필요할 때, 신용카드 한도를 안전하고 간편하게 현금으로 바꿔드립니다.

    낮은 수수료, 신용등급 걱정 없이 즉시 입금, 모든 카드사 이용 가능

  3. Link exchange is nothing else except iit is only placing the other person’s blog link on your page at appropriate place
    and other person will also do similar for you.