你的函数square必须是一个全局定义的函数,以便像你定义的那样从你的HTML中调用它。但是这块代码:
(function() {
var square;
square = function(x) {
return alert(x * x);
};
}).call(this);
没有定义全局函数,因此无法找到该符号。实际上,函数平方只在您的IIFE中定义,并且在其他地方不可用。如果你想让它全局可用,您可能也只是上面块改成这样:
window.square = function(x) {
return alert(x * x);
}
或者,你可以这样做:
(function() {
this.square = function(x) {
return alert(x * x);
};
}).call(this);
或者,显然是在CoffeeScript中,@符号是对于this.
的简写,因此您可以使用此:
(function() {
@square = function(x) {
return alert(x * x);
};
}).call(this);
甚至只是这样的:
@square = function(x) {
return alert(x * x);
};
更多信息请参阅本其他答案:How do I define global variables in CoffeeScript?
更妙的是不使用这种调用方法。如果您使用事件侦听器,那么您不必使该函数成为全局的。
从你的pastebin看来,'square'被封闭在关闭中,所以永远不会进入全局命名空间 –