mahemoff
mahemoff

Reputation: 46429

CoffeeScript variable scope

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.)

Upvotes: 4

Views: 6333

Answers (3)

xaxxon
xaxxon

Reputation: 19771

You can say `var counter;` with backticks and that is passed literally through to the generated javascript.

When you have a problem like this, look at the generated javascript. It will be extremely clear that the variable scope is lexically limited to the function.

Looking at the generated javascript is often a good way to understand what the behavior of coffeescript constructs is.

Upvotes: 0

Marcel M.
Marcel M.

Reputation: 2376

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

obj = 
  init: ->
    @counter = 0
  inc: ->
    @counter += 1

Upvotes: 4

loganfsmyth
loganfsmyth

Reputation: 161477

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

counter = null
init = ->
  counter = 0
inc = ->
  counter += 1

Upvotes: 14

Related Questions