开发者

Using closure for private variables in coffeescript

开发者 https://www.devze.com 2023-04-11 03:57 出处:网络
In JavaScript, one would define a private member variable by making it a local variable in a function that returns a closure:

In JavaScript, one would define a private member variable by making it a local variable in a function that returns a closure:

var count = (function(){
  var i = 0;开发者_开发问答
  return function (){ return i++; }
})();

This involves a define-function-then-call-it idiom that is fairly common in JavaScript, but I do not know how it translates in CoffeeScript. Any ideas?


You can use the do keyword

count = do ->
  i = 0
  -> i++


As Brian said, the do keyword is best. You can also use parens, just as in JavaScript:

count = (->
  i = 0
  -> i++
)()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号