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

查看:170
本文介绍了CoffeeScript中的函数声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在CoffeeScript中,如果我定义一个函数使用:

  a =(c) c = 1 

我只能获得函数表达式

  var a; 
a = function(c){
return c = 1;
};但是,我个人经常使用函数声明,例如:

p>

  function a(c){
return c = 1;
}

我使用第一种形式,但我想知道是否有方法在CoffeeScript生成函数声明。如果没有这样的方式,我想知道为什么CoffeeScript避免这样做。我不认为JSLint会声明一个错误,只要函数声明在作用域的顶部。

解决方案

p> CoffeeScript在一个地方使用函数声明(又名命名函数): class 定义。例如,

  class Foo 

编译为

  var Foo; 
Foo =(function(){
function Foo(){}
return Foo;
})();

CoffeeScript在其他地方不使用函数声明的原因,根据常见问题


。最初每个函数都可以有一个合理的名称检索它给一个,但IE版本8和下来有范围问题,其中命名的函数被视为声明和表达式。有关详情,请参见


总之:使用函数声明不小心会导致IE(pre-9)和其他JS环境之间的不一致,所以CoffeeScript避开了它们。


I notice that in CoffeeScript, if I define a function using:

a = (c) -> c=1

I can only get the function expression:

var a;
a = function(c) {
    return c = 1;
};

But, personally I often use function declaration,for example:

function a(c) {
    return c = 1;
}

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 uses function declarations (aka "named functions") in just one place: class definitions. For instance,

class Foo

compiles to

var Foo;
Foo = (function() {
  function Foo() {}
  return Foo;
})();

The reason CoffeeScript doesn't use function declarations elsewhere, according to the FAQ:

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.

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天全站免登陆