Functions In CoffeeScript

2019-01-16 09:17发布

问题:

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?

回答1:

You need to export the convert function to the global scope.
See How can Coffescript access functions from other assets?

window.convert = (num1, num2, num3) ->
  num1 + num2 * num3


回答2:

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

window.App = {}

Then, you can have access to App globally and add all your stuff there. the function convert can now be expressed this way:

App.convert = convert = (a, b, c) -> a + b * c

Then, to call the function within the local scope

convert 1,2,3

And now globally

App.convert 1,2,3


回答3:

At the top level of your coffeescript file, this (aka @) should refer to window. So to attach it here, you could use the shorthand:

@convert = (num1, num2, num3) -> num1 + num2 * num3

Note that this pollutes the global namespace, though. The solution posted by jm- is more prudent. But you can replace

window.App = {}

with

@App = {}

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.



回答4:

window.convert = (num1, num2, num3) ->
  num1 + num2 * num3


回答5:

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/

convert = (num1, num2, num3) ->
  num1 + num2 * num3


回答6:

convert = (num1, num2, num3) -> num1 + num2 * num3