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 中的函数声明


基础教程推荐
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在for循环中使用setTimeout 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 动态更新多个选择框 2022-01-01