I'm trying to convert a function
from Javascript to CoffeeScript. This is the code:
function convert(num1, num2, num3) {
return num1 + num2 * num3;
}
But how I can do that in CoffeeScript?
I'm trying to run the function from an HTML source like this:
<script type="text/javascript" src="../coffee/convert.js"></script>
<script type="text/javascript">
convert(6, 3, 10);
</script>
But it won't work and I get an error saying: ReferenceError: Can't find variable: convert
How to correct this?
At the top level of your coffeescript file, this (aka @) should refer to window. So to attach it here, you could use the shorthand:
Note that this pollutes the global namespace, though. The solution posted by jm- is more prudent. But you can replace
with
The benefit of using @ is that it refers to global in node.js, so you can use the same code to expose your functions in both browser and serverside environments.
@lawnsea answer is great.
I just want to add some thoughts.
Instead of polluting the global namespace, I prefer to add just one variable to the
window
object.Then, you can have access to
App
globally and add all your stuff there. the functionconvert
can now be expressed this way:Then, to call the function within the local scope
And now globally
You need to export the convert function to the global scope.
See How can Coffescript access functions from other assets?
You should check these awesome slides just released today by godfoca http://www.slideshare.net/godfoca/lets-have-a-cup-of-coffeescript Also, you can try code out through-the-web at http://jashkenas.github.com/coffee-script/