如何在Coffeescript中使用setTimeout()

raf*_*man 20 coffeescript

我似乎无法使用setTimeout()来调用我自己的函数之一.我可以使用setTimeout来调用alert(),但不能使用我自己编写的函数.这是重现问题的最简单的代码:

我有以下coffeeScript

    setTimeout(run, 1000)

    run = () ->
        console.log("run was called!")
Run Code Online (Sandbox Code Playgroud)

这会生成以下Javascript

    // Generated by CoffeeScript 1.6.3
    (function() {
      var run;

      setTimeout(run, 1000);

      run = function() {
        return console.log("run was called!");
      };

    }).call(this);
Run Code Online (Sandbox Code Playgroud)

控制台上没有任何内容.

Pet*_*ons 23

run = () ->
    console.log("run was called!")
setTimeout(run, 1000)
Run Code Online (Sandbox Code Playgroud)

你依靠javascript函数提升语法function run(){}声明的函数,但是coffeescript将它们声明为变量:var run = function(){},所以你必须在引用它之前定义它,否则它仍然是undefined你传递给它的时候setTimeout.


cwd*_*cwd 16

匿名选项:

彼得是完全正确的.但您也可以在setTimeout不声明变量的情况下使用:

setTimeout ->
    console.log 'run was called!'
, 1000
Run Code Online (Sandbox Code Playgroud)

产量:

(function() {
    setTimeout(function() {
        return console.log("run was called!")
    }, 1e3)
}).call(this);
Run Code Online (Sandbox Code Playgroud)