当前位置: 动力学知识库 > 问答 > 编程问答 >

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

网友答案:

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

counter = null
init = ->
  counter = 0
inc = ->
  counter += 1
网友答案:

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

obj = 
  init: ->
    @counter = 0
  inc: ->
    @counter += 1
网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: