最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why coffeescript use « return » statement everywhere? - Stack Overflow

programmeradmin2浏览0评论

When writing something like that:

$(document).ready ->
  doSomething()

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

is piled 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 ?

When writing something like that:

$(document).ready ->
  doSomething()

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

is piled 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 ?

Share Improve this question asked Mar 24, 2013 at 12:57 m4tm4tm4tm4t 2,3811 gold badge21 silver badges37 bronze badges 1
  • just to write uniform/nicely script and return alert('Nothing to do'); == return; – Grijesh Chauhan Commented Mar 24, 2013 at 13:02
Add a ment  | 

2 Answers 2

Reset to default 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.

Coffeescript, like Ruby, always returns the last statement in a function. The last statement will always evaluate to either a value (string, array, integer, etc) or null. In either case, it's perfectly valid to return the result.

To answer 'why' coffescript does this with all functions, instead of only ones where there is a value, it's simply because in many cases, Coffeescript can't tell when the last statement will evaluate to a value or null. It's much safer and simpler to always have the return statement there, and there aren't any negative consequences. If you don't care what the function returns, you can just ignore the returned value.

发布评论

评论列表(0)

  1. 暂无评论