Reputation: 61
I have this main coffeescript code:
<script src="libs/coffeeScript.js"> </script>
<script src="maths.coffee"> </script>
<script type="text/coffeescript">
document.write math.cube 2
</script>
and this code in the "maths.coffee" file:
math ={}
math.cube=(x)->x*x*x
Why can I not access the cube function?
I already tried a lot of solutions found on this site, without success.
Upvotes: 1
Views: 1384
Reputation: 5515
When a CoffeeScript file is compiled into JavaScript it is wrapped in an IIFE. So the JS code you end up with looks something like this:
(function () {
var math = {};
math.cube = function(x) {
return x * x * x;
};
})();
What this means is that the function is only scoped within that IIFE, which prevents polution of the global namespace.
Because you are including your CoffeeScript inline, you need to explicitly expose any functions you want to use in other files onto a global object, e.g. window
math = {}
math.cube = (x) -> x * x * x
window.math = math
Alternatively, you could compile your CoffeeScript before hand, and pass in the --bare
option. Then just include the JavaScript file with your page.
Upvotes: 2