自执行咖啡脚本

Self executing coffeescript

自调用 Coffeescript

$ -> 
  alert "Hello CoffeeScript!"

编译为

$(function() {
  return alert("Hello CoffeeScript!");
});

现在,相同的代码 -- $ 替换为任何其他变量 -->

hello= -> 
  alert "Hello CoffeeScript!"

以上代码 - 不会自行执行。

如何给一个$变量启用自执行(不包括jQuery lib)?(是jQuery发挥作用在这里?)

我知道你必须使用 do 才能在 coffeescript 中使用自调用函数 --- 这不是我的问题(请不要重复它)。

-coffeescript 初学者

代码不是自动执行的。它只是给 jQuery 一个函数引用。 jQuery 稍后会在 DOM 准备就绪时调用该函数(如果已经准备就绪,则立即调用)。

详情in the jQuery documentation.

How does giving a $ variable enable self execution(jQuery lib not included)?

如果正在调用该函数,jQuery 显然 包含 (或其他定义函数并将其附加到 $ 并调用你传递它的功能)。

(is jQuery is playing a role here?)

是的。


I know you've to use do to have self invoking functions in coffeescript

如果你的意思是立即调用而不是自我调用(一个常见的误称),不,你没有:

(() ->
  alert 'Hello!'
)()

...转换为:

(function() {
  return alert('Hello!');
})();

...它定义了一个函数并立即调用它。

或者如果你真的想 self-调用(例如,递归):

(foo = (n) ->
  alert 'Call ' + n
  if n > 0
    foo(n - 1);
)(10)

...转换为:

var foo;

(foo = function(n) {
  alert('Call ' + n);
  if (n > 1) {
    return foo(n - 1);
  }
})(10);

...它定义了一个调用自身 10 次的函数。

不,$ 标识符没有什么特别之处。您的片段之间的实际区别是标识符后的 = - 没有,它使用函数作为参数调用它,函数被分配。

hello -> 
  alert "Hello CoffeeScript!"
// compiles to:
hello(function() {
  return alert("Hello CoffeeScript!");
});

hello = -> 
  alert "Hello CoffeeScript!"
// compiles to:
var hello;
hello = function() {
  return alert("Hello CoffeeScript!");
};

因此,如果您的 hello 函数确实调用了给定的回调(如 $ does),您的函数表达式将在第一种情况下执行(没有赋值)。

请注意,这不是 "self-invocation",因为 hello/$ 会调用该函数。对于 IIFE (which is usually referred to as "self-invoking"), you'd use Coffeescripts do keyword.