Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript variable scope

Tags:

coffeescript

Is there any way to declare a variable at "file" scope (which will be closured by CS), without initializing it? A contrived example:

init = ->
  counter = 0

inc = ->
  counter += 1

This won't work, because you need to declare "counter". Adding "counter = 0" to the top would make it work, but the "= 0" is unnecessary. (A more realistic example would involve something that accesses the DOM on page load - there's no way to correctly initialize it in "file" scope.)

like image 522
mahemoff Avatar asked Dec 03 '22 00:12

mahemoff


2 Answers

You'll have to define it on the outer scope, as you mentioned.

counter = null
init = ->
  counter = 0
inc = ->
  counter += 1
like image 135
loganfsmyth Avatar answered Dec 21 '22 23:12

loganfsmyth


If your functions where part of an object you could use @counter, like this:

obj = 
  init: ->
    @counter = 0
  inc: ->
    @counter += 1
like image 39
Marcel M. Avatar answered Dec 22 '22 00:12

Marcel M.