How do I define global variables in CoffeeScript?

后端 未结 8 2045
说谎
说谎 2020-11-22 05:41

On Coffeescript.org:

bawbag = (x, y) ->
    z = (x * y)

bawbag(5, 10) 

would compile to:

var bawbag;
bawbag = function(         


        
相关标签:
8条回答
  • 2020-11-22 05:56

    To me it seems @atomicules has the simplest answer, but I think it can be simplified a little more. You need to put an @ before anything you want to be global, so that it compiles to this.anything and this refers to the global object.

    so...

    @bawbag = (x, y) ->
        z = (x * y)
    
    bawbag(5, 10)
    

    compiles to...

    this.bawbag = function(x, y) {
      var z;
      return z = x * y;
    };
    bawbag(5, 10);
    

    and works inside and outside of the wrapper given by node.js

    (function() {
        this.bawbag = function(x, y) {
          var z;
          return z = x * y;
        };
        console.log(bawbag(5,13)) // works here
    }).call(this);
    
    console.log(bawbag(5,11)) // works here
    
    0 讨论(0)
  • 2020-11-22 05:56

    To add to Ivo Wetzel's answer

    There seems to be a shorthand syntax for exports ? this that I can only find documented/mentioned on a Google group posting.

    I.e. in a web page to make a function available globally you declare the function again with an @ prefix:

    <script type="text/coffeescript">
        @aglobalfunction = aglobalfunction = () ->
             alert "Hello!"
    </script>
    
    <a href="javascript:aglobalfunction()" >Click me!</a>
    
    0 讨论(0)
提交回复
热议问题