Coffeescript 函数未定义

use*_*522 3 javascript coffeescript

我创建了一个 coffeescript 函数square=(x)->alert x*x
它被编译成这个 javascript

(function() {
  var square;

  square = function(x) {
    return alert(x * x);
  };

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

所以如果我写这个代码 <button onclick="square(5)">编译器说这square()是未定义的。怎么了?

jfr*_*d00 5

您的函数 square 必须是一个全局定义的函数,才能像您定义的那样从 HTML 中调用它。但是这段代码:

(function() {
  var square;

  square = function(x) {
    return alert(x * x);
  };

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

没有全局定义函数,因此找不到符号。事实上,函数 square 仅在您的 IIFE 中定义,在其他任何地方都不可用。如果您希望它在全球范围内可用,您也可以将上面的块更改为:

window.square = function(x) {
    return alert(x * x);
}
Run Code Online (Sandbox Code Playgroud)

或者,你可以这样做:

(function() {
    this.square = function(x) {
       return alert(x * x);
    };
}).call(this);
Run Code Online (Sandbox Code Playgroud)

或者,显然在 CoffeeScript 中,@ 符号是缩写,this.因此您可以使用它:

(function() {
    @square = function(x) {
       return alert(x * x);
    };
}).call(this);
Run Code Online (Sandbox Code Playgroud)

甚至只是这个:

@square = function(x) {
   return alert(x * x);
};
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅其他答案:如何在 CoffeeScript 中定义全局变量?


更好的是不要使用这种调用方法。如果您改用事件侦听器,则根本不必使该函数成为全局函数。