coffee为什么每次都会生成 return语句
发布于 10 年前 作者 firefox 3590 次浏览 最后一次编辑是 8 年前 来自 问答
alert(
  try
    nonexistent / undefined
  catch error
    "And the error is ... #{error}"
)

# 如果我不想在 catch 语句中出现 return 怎么处理?
# 为什么它每次都会在代码块的最后一句生成 return ?
var error;

alert((function() {
  try {
    return nonexistent / void 0;
  } catch (_error) {
    error = _error;
    return "And the error is ... " + error; 
  }
})());
7 回复

在结束的地方加一句 return,就不会生成return了

@thondery 谢谢,这样写但感觉有点别扭,不知有没更好的方式?

函数式风格的编程语言就是这样,它们的函数都会返回最后那个值,ruby 和 lisp 也这样。

@alsotang 函数式语言每个语句都有一个值没错,但不只是最后一句返回一个值。但是生成每次最后一句都是 return 语句,比如在 try 语句 return ,catch 也有一个 return ,finally 也生成一个 return。这样如果运行时出错,逻辑不就很容易混乱,所以我才产生这个疑问?

@firefox 目前没有遇到这种问题,在我担心会return出现错误的时候,我会手动加上return,实际上并没有验证如果不加会不会出错。

@think2011 我现在也是打算这样写,只让它出现一次 return :

catchErrors = ->
    result = ''
    try
        nonexistent / undefined
        result = 'things I want to return'
        return
    catch error
        console.log error
        return
    finally
        console.log 'done'
        return result

可以看一下这个issue的讨论:https://github.com/jashkenas/coffeescript/issues/2477

jashkenas大神明确表示不会改变这个行为,CS的理念是expression-oriented的,即任何代码片段都应该是一个有意义的expression,绝大部分情况下默认的return都不会造成任何问题,不用管就是了。甚至有人已经提了很有意思的PR,也被拒绝了 https://github.com/jashkenas/coffeescript/pull/2726 ,jashkenas的拒绝理由:

I’m afraid I’m going to have to close this for the same reasons as before – It’s a great PR, and a great example implementation, but the reasoning for the current function options haven’t changed. Ideally every function returns a meaningful value – if it’s asynchronous, maybe a promise – even if that value is just true or null, or this for chaining. And if you really don’t want to return a value, the nicest place to put that information is at the end of the function, where the value normally comes out. Anyhow, it’s all been said before ;)

这种理念对强迫症患者来说会觉得很别扭,可实际上一旦接受了这种设定,还觉得挺带感的……

有个回复我非常认同,CS不是JS的一个Wrapper,而是JS Runtime上的另一门不同的,并且更好的语言。所以不要去纠结生成的JS代码了,按CS本身提供的语法、语义和编程理念来写代码,能写出更优雅的代码,而且能得到更好的编程思维

对于你这个问题,这些return只要不造成影响,不要管就是了

回到顶部