CoffeeScript 中的函数声明 [英] Function declaration in CoffeeScript

查看:16
本文介绍了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 中的函数声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆