Reputation: 916
This is getting ridiculous...
Why do I get an error when I try to do this?
#...codecodecode...
g = generateGuid()
#...codecodecode...
generateGuid = ->
"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace /[xy]/g, (c) ->
r = Math.random() * 16 | 0
v = (if c is "x" then r else (r & 0x3 | 0x8))
v.toString 16
All I want to do is call a private function...
Upvotes: 2
Views: 361
Reputation: 77426
driis is correct. To expand on his answer: You may be used to the JavaScript idiom
function generateGuid() { ... }
which allows you to call generateGuid
from anywhere within its scope (even before its definition). CoffeeScript doesn't do this; instead, it compiles to
var generateGuid = function() { ... }
There are several reasons for doing this, but the long and short of it is that functions obey the same scoping rules as all other variables. Before a value has been assigned to generateGuid
, generateGuid()
is an attempt to call undefined
.
Note that, due to the way asynchronous callbacks work in JavaScript, this will work:
setTimeout (->
g = generateGuid
# ...codecodecode...
), 0
generateGuid = -> ...
Upvotes: 5
Reputation: 164341
You are trying to call the function before it's defined. This works:
#...codecodecode...
#...codecodecode...
generateGuid = ->
"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace /[xy]/g, (c) ->
r = Math.random() * 16 | 0
v = (if c is "x" then r else (r & 0x3 | 0x8))
v.toString 16
g = generateGuid()
In case this is surprising to you, remember that Coffeescript compiles to Javascript - in fact, it is not much more than syntactic sugar over some Javascript. Most of the rules that apply in Javascript will also hold true in Coffeescript.
Upvotes: 3