编写CoffeeScript时编译Javascript中不必要的return关键字

时间:2014-08-05 05:50:37

标签: javascript coffeescript return

这段代码是咖啡脚本,当翻译成JS时,它会在_load函数之前给出“return”关键字。我试过移动函数并将循环更改为单行程似乎没有帮助 请帮忙

(->
  resourceCache = {}
  loading = []
  readyCallbacks = []
  # load image url or array of image urls
  load = (urlOrArr) ->
    if (urlOrArr instanceof Array)
      for url in urlOrArr
        _load(url)
    else
      _load(urlOrArr)

  _load = (url) ->
    if(resourceCache[url])
      resourceCache[url]
    else
      img = new Image()
      img.onload = ->
        resourceCache[url] = img
        if(isReady())
          (func) -> func() for el in readyCallbacks
      resourceCache[url] = false
      img.src = url

.
.
.





)()

这是js

(function() {
    var load, loading, readyCallbacks, resourceCache, _load;
    resourceCache = {};
    loading = [];
    readyCallbacks = [];
    load = function(urlOrArr) {
      var url, _i, _len, _results;
      if (urlOrArr instanceof Array) {
        _results = [];
        for (_i = 0, _len = urlOrArr.length; _i < _len; _i++) {
          url = urlOrArr[_i];
          _results.push(_load(url));
        }
        return _results;
      } else {
        return _load(urlOrArr);
      }
    };
    return _load = function(url) {
      var img;
      if (resourceCache[url]) {
        return resourceCache[url];
      } else {
        img = new Image();
        img.onload = function() {
          resourceCache[url] = img;

1 个答案:

答案 0 :(得分:2)

"Everything is an Expression (at least, as much as possible)"。函数的最后一个表达式是它的返回值。

为了强制执行该操作,编译器在函数的每个执行分支的末尾静默添加隐式return语句。

因此,JS中的return _load ...是预期的,因为外部函数的最后一个语句是函数定义(_load = (url) -> ...)。


如果由于某种原因,您真的不希望返回内部函数,则必须在函数末尾添加一个额外的语句。请比较这些不同的案例:

1:隐含退货(您的情况)

->
    "Outer function"

    inner = ->
        "Inner function

编译成

(function() {
  (function() {
    "Outer function";
    var inner;
    return inner = function() {
      return "Inner function";
    };
  });

}).call(this);

2:使用显式返回语句

->
    "Outer function"

    inner = ->
        "Inner function"

    return

编译成

// Generated by CoffeeScript 1.7.1
(function() {
  (function() {
    "Outer function";
    var inner;
    inner = function() {
      return "Inner function";
    };
  });

}).call(this);

额外的return语句实际上会使外部函数返回值undefined。如果您愿意,可以使用return undefined甚至简单地undefined代替裸return来明确说明。编译后的代码会略有不同(显式return void 0),但行为将是相同的。

3:显式undefined表达式

->
    "Outer function"

    inner = ->
        "Inner function"

    undefined
    # or `return undefined`

编译成

(function() {
  function() {
    "Outer function";
    var inner;
    inner = function() {
      return "Inner function";
    };
    return void 0;
  };
}).call(this);