如何跨 CoffeeScript 函数访问变量?
How to access a variable across CoffeeScript functions?
我在 Rails 中使用 CS。如果我有:
foo = ->
...
bar = ->
...
->
someCount = 123
foo()
bar()
如何在 foo()
和 bar()
中访问 someCount
而不是直接将其作为参数传递?
我认为这需要将 someCount
声明为全局变量。我看了this and this,但我不明白如何实现它。我试过了:
root = exports ? this
root.someCount = 123
但是在 foo()
中我无法通过 someCount
(someCount 未定义)或 root.someCount
(root 未定义).
您只需在其他函数也在的范围内声明 somecount
:
somecount = null
foo = ->
alert somecount
bar = ->
alert somecount
->
someCount = 123
foo()
bar()
我在 Rails 中使用 CS。如果我有:
foo = ->
...
bar = ->
...
->
someCount = 123
foo()
bar()
如何在 foo()
和 bar()
中访问 someCount
而不是直接将其作为参数传递?
我认为这需要将 someCount
声明为全局变量。我看了this and this,但我不明白如何实现它。我试过了:
root = exports ? this
root.someCount = 123
但是在 foo()
中我无法通过 someCount
(someCount 未定义)或 root.someCount
(root 未定义).
您只需在其他函数也在的范围内声明 somecount
:
somecount = null
foo = ->
alert somecount
bar = ->
alert somecount
->
someCount = 123
foo()
bar()