4

I create a coffeescript function square=(x)->alert x*x
It's compiled into this javascript

(function() {
  var square;

  square = function(x) {
    return alert(x * x);
  };

}).call(this);

So if i write this code <button onclick="square(5)"> compiler says that square() is undefined. What's wrong?

Darin Kolev
  • 3,401
  • 13
  • 31
  • 46
  • From your pastebin, it looks like `square` is kept within the closure so never gets out into the global namespace – Paul S. Apr 06 '14 at 15:57

1 Answers1

5

Your function square has to be a globally defined function in order to call it from your HTML like you have defined. But this block of code:

(function() {
  var square;

  square = function(x) {
    return alert(x * x);
  };

}).call(this);

Does not define the function globally, therefore the symbol can't be found. In fact, the function square is only defined within your IIFE and isn't available anywhere else. If you want it available globally, you may as well just change the above block to this:

window.square = function(x) {
    return alert(x * x);
}

Or, you could do this:

(function() {
    this.square = function(x) {
       return alert(x * x);
    };
}).call(this);

Or, apparently in CoffeeScript, the @ sign is a shorthand for this. so you can use this:

(function() {
    @square = function(x) {
       return alert(x * x);
    };
}).call(this);

or even just this:

@square = function(x) {
   return alert(x * x);
};

See this other answer for more info: How do I define global variables in CoffeeScript?


Even better would be to not use this calling method. If you use event listeners instead, then you don't have to make the function be global at all.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • but i write a coffeescript function globaly, and it strangly compiled into anonymous function. What's wrong? – user2513522 Apr 06 '14 at 16:00
  • @user2513522 - sorry, I don't know a lot about coffeescript, but I've modified my recommendation in my answer to force it to be global. – jfriend00 Apr 06 '14 at 16:03
  • @user2513522 - added several other CoffeeScript options. – jfriend00 Apr 06 '14 at 16:12
  • the decision is to compile coffeescript by this command `coffee -b --compile somefile.coffee whatever.js` I has written first time at stackoverflow, and i surprised so fast answer. Thank you, and sorry for my poor english. – user2513522 Apr 06 '14 at 16:22
  • 1
    @user2513522 - since you're new here on StackOverflow, do you know that if someone helps you find your answer, you can mark their answer as the accepted answer by clicking the green checkmark to the left of their answer. That will reward them with some reputation points for helping you and earn you some reputation points for following the desired procedure. Reputation points will earn you privileges on the site. – jfriend00 Apr 06 '14 at 16:25