我注意到在 CoffeeScript 中,如果我定义一个函数使用:
a = (c) -> c=1
我只能得到函数表达式:
var a;
a = function(c) {
return c = 1;
};
但是,我个人经常使用函数声明,例如:
function a(c) {
return c = 1;
}
我确实使用第一种形式,但我想知道 CoffeeScript 中是否有生成函数声明的方法。如果没有这种方法,我想知道为什么 CoffeeScript 避免这样做。我不认为 JSLint 会大喊声明错误,只要函数是在范围的顶部声明的。
最佳答案
CoffeeScript 只在一个地方使用函数声明(又名“命名函数”):class
定义。例如,
class Foo
编译为
var Foo;
Foo = (function() {
function Foo() {}
return Foo;
})();
根据FAQ,CoffeeScript 不在别处使用函数声明的原因:
Blame Microsoft for this one. Originally every function that could have a sensible name retrieved for it was given one, but IE versions 8 and down have scoping issues where the named function is treated as both a declaration and an expression. See this for more information.
简而言之:粗心地使用函数声明会导致 IE(pre-9)和其他 JS 环境之间的不一致,因此 CoffeeScript 避开了它们。
关于javascript - CoffeeScript 中的函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6548750/