Top-level variables aren't globally-scoped and return values are mandatory in CoffeeScript

前端 未结 3 615
粉色の甜心
粉色の甜心 2021-01-21 04:19
funName = () ->
  $(\".foo\").addClass(\"bar\");

Compiles into the scope of an anonymous function. Calling funName from the console res

相关标签:
3条回答
  • 2021-01-21 05:02

    I know this may be an older thread, but I've encountered the same problem and noticed an interesting command you can add into the compiler enviroment to fix this problem.

    The command -b or --bare is used to compile the JavaScript without the top-level function safety wrapper. After I added that command when I compiled my CoffeeScript file, it removed that odd wrapper:

    (function() {
        var funName;
        funName = function() {
           return $(".foo").addClass("bar");
        };
     }).call(this);
    

    I use WebStorm as my IDE enviroment and this is my compiler statement I use:

    --compile --bare $FileName$
    
    0 讨论(0)
  • 2021-01-21 05:22

    Mike has answered the main question here. The modular wrapper a common point of confusion for CoffeeScript newcomers, as illustrated by these related questions:

    • How do I define global variables in CoffeeScript?
    • Why use the javascript function wrapper (added in coffeescript) ".call(this)"
    • Getting rid of CoffeeScript's closure wrapper

    As to your other question: If you don't want a function to return anything, simply make the last line of that function either return by itself or, equivalently, undefined. Either will compile to a function with no return. For instance:

    funName = ->
      $(".foo").addClass "bar"
      return
    

    compiles to

    var funName;
    funName = function() {
      $(".foo").addClass("bar");
    };
    

    Note that there is an ongoing discussion (issue 899) about a possible alternative syntax for defining no-return functions. If the current proposal were accepted, you'd be able to write your function as

    funName = -/> $(".foo").addClass "bar"
    

    If you like that syntax, you should voice your support for it.

    0 讨论(0)
  • 2021-01-21 05:24

    If you want to create a global funName try using root = exports ? this and then root.funName = ... as described at How do I define global variables in CoffeeScript?

    0 讨论(0)
提交回复
热议问题