javascript - Coffeescript 在嵌套循环中关闭此引用列表

标签 javascript coffeescript

这是我在 CoffeeScript 上观察到的一些有趣的东西。

TLDR:{

我们知道粗箭头 (=>) 生成一个闭包保存对 this 的引用并且 @ 的每个引用都将被替换this 的原始值。因此,以下 coffeescript 代码:

=>
  @sth

将产生以下内容:

(function(_this) {
  return (function() {
    return _this.sth;
  });
})(this);

注意 _this.sth

}

但这是我发现的极端情况:

=>
  for a in sth
    for b in @sth
      sth

计算结果为:

(function(_this) {
  return (function() {
    var a, b, i, len, results;
    results = [];
    for (i = 0, len = sth.length; i < len; i++) {
      a = sth[i];
      results.push((function() {
        var j, len1, ref, results1;
        ref = this.sth;
        results1 = [];
        for (j = 0, len1 = ref.length; j < len1; j++) {
          b = ref[j];
          results1.push(sth);
        }
        return results1;
      }).call(_this));
    }
    return results;
  });
})(this);

这有点长,但问题是内部循环遍历 this.sth 而不是 _this.sth

内循环的确切行是:

ref = this.sth;
results1 = [];
for (j = 0, len1 = ref.length; j < len1; j++) {
  b = ref[j];

这是正常行为还是错误?

最佳答案

仔细看看内部循环:

results.push((function() {
  var j, len1, ref, results1;
  ref = this.sth;
  // Loop stuff goes here...
}).call(_this));

内部循环包含在一个函数中(作为循环理解代码的一部分),该函数使用 Function.prototype.call 求值。 :

The call() method calls a function with a given this value and arguments provided individually.

call 是用 _this(来自 => 的隐藏/绑定(bind) @)调用的,所以 this 在该函数中实际上是 _this 并且一切正常。

如果您通过显式返回任何内容来抑制理解代码:

=>
  for a in sth
    for b in @sth
      sth
  return

然后你会看到你最初期待的ref = _this.sth:

(function(_this) {
  return (function() {
    var a, b, i, j, len, len1, ref;
    for (i = 0, len = sth.length; i < len; i++) {
      a = sth[i];
      ref = _this.sth; # <---------------------------
      for (j = 0, len1 = ref.length; j < len1; j++) {
        b = ref[j];
        sth;
      }
    }
  });
})(this);

关于javascript - Coffeescript 在嵌套循环中关闭此引用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43311114/

相关文章:

javascript - 我的 if 语句不起作用

javascript - html javascript中的无限滚动

javascript - jQuery闪烁效果按钮动画(提供fiddle)

javascript - 当 div 触摸浏览器顶部时添加类

terminal - 将多个 Coffeescript 文件合并到一个文件中? (多个子目录)

javascript - 在 javascript 环境中执行

javascript - jqplot:条形图的图例数据格式

javascript - 节点JS : Pass object from HTML to Server

javascript - Node.js 和 ES6

javascript - Coffeescript 闭包和随机数数组