3

When writing something like that:

$(document).ready ->
  doSomething()

doSomething = ->
  alert('Nothing to do')

is compiled into

$(document).ready(function() {
  return doSomething();
});

doSomething = function() {
  return alert('Nothing to do');
};

In my understand, the return statement is for values (string, array, integer...)

Why coffeescript do that ?

4

2 回答 2

8

CoffeeScript uses an implicit return if none is specified.

CS returns the value of the last statement in a function. This means the generated JS will have a return of the value of the last statement since JS requires an explicit return.

the return statement is for values (string, array, integer...)

Yes, and those values may be returned by calling a function, like doSomething() or alert() in your example. That the values are the result of executing a method is immaterial.

于 2013-03-24T13:03:29.977 回答
1

Coffeescript 和 Ruby 一样,总是返回函数中的最后一条语句。最后一条语句将始终计算为一个值(字符串、数组、整数等)或null. 无论哪种情况,返回结果都是完全有效的。

要回答'为什么' coffescript 对所有函数都这样做,而不仅仅是那些有值的函数,这仅仅是因为在许多情况下,Coffeescript 无法判断最后一条语句何时会评估为一个值或null. 始终将return声明放在那里会更安全、更简单,并且不会产生任何负面后果。如果你不关心函数返回什么,你可以忽略返回值。

于 2013-03-24T13:05:32.450 回答