javascript - Coffeescript function is undefined -
this question has answer here:
i create coffeescript function square=(x)->alert x*x
it's compiled javascript
(function() { var square; square = function(x) { return alert(x * x); }; }).call(this);
so if write code <button onclick="square(5)">
compiler says square()
undefined. what's wrong?
your function square has globally defined function in order call html have defined. block of code:
(function() { var square; square = function(x) { return alert(x * x); }; }).call(this);
does not define function globally, therefore symbol can't found. in fact, function square defined within iife , isn't available anywhere else. if want available globally, may change above block this:
window.square = function(x) { return alert(x * x); }
or, this:
(function() { this.square = function(x) { return alert(x * x); }; }).call(this);
or, apparently in coffeescript, @ sign shorthand this.
can use this:
(function() { @square = function(x) { return alert(x * x); }; }).call(this);
or this:
@square = function(x) { return alert(x * x); };
see other answer more info: how define global variables in coffeescript?
even better not use calling method. if use event listeners instead, don't have make function global @ all.
Comments
Post a Comment