Function declaration in CoffeeScript(CoffeeScript 中的函数声明)
问题描述
我注意到在 CoffeeScript 中,如果我使用以下方法定义函数:
I notice that in CoffeeScript, if I define a function using:
a = (c) -> c=1
我只能得到函数表达式:
var a;
a = function(c) {
return c = 1;
};
但是,我个人经常使用函数声明,例如:
But, personally I often use function declaration,for example:
function a(c) {
return c = 1;
}
我确实使用第一种形式,但我想知道 CoffeeScript 中是否有一种方法可以生成函数声明.如果没有这样的方法,我想知道为什么 CoffeeScript 避免这样做.只要函数在作用域的顶部声明,我认为 JSLint 不会抱怨声明错误.
I do use the first form, but I'm wondering if there is a way in CoffeeScript generating a function declaration. If there is no such way, I would like to know why CoffeeScript avoid doing this. I don't think JSLint would holler an error for declaration, as long as the function is declared at the top of the scope.
推荐答案
CoffeeScript 只在一个地方使用函数声明(又称命名函数"):class
定义.例如,
CoffeeScript uses function declarations (aka "named functions") in just one place: class
definitions. For instance,
class Foo
编译成
var Foo;
Foo = (function() {
function Foo() {}
return Foo;
})();
根据FAQ:
将此归咎于微软.最初,每个可以为其检索到合理名称的函数都被赋予了一个,但 IE 8 及以下版本存在范围问题,其中命名函数被视为声明和表达式.请参阅 this 了解更多信息.
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(9 之前)和其他 JS 环境之间的不一致,因此 CoffeeScript 避开了它们.
In short: Using function declarations carelessly can lead to inconsistencies between IE (pre-9) and other JS environments, so CoffeeScript eschews them.
这篇关于CoffeeScript 中的函数声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:CoffeeScript 中的函数声明


- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01