【问题标题】:for loop assigns same functon everytime in Livescriptfor循环每次在Livescript中分配相同的函数
【发布时间】:2016-09-23 10:17:43
【问题描述】:

我希望“x's”结果、“y's”结果和“z's”结果相同:

在 Livescript 中:

x = 
  a: -> 3 
  b: -> 4 

y = {}
for k, v of x 
  console.log "key: ", k, "val: ", v 
  y[k] = -> v.call this 


console.log "y is: ", y 
console.log "x's: ", x.a is x.b   # should return false, returns false
console.log "y's: ", y.a is y.b   # should return false, returns true

z = {}
z['a'] = -> 
  x.a.call this 

z['b'] = -> 
  x.b.call this 

console.log "z's: ", z.a is z.b  # should return false, returns false

在 Javascript 中:

var x, y, k, v, z;
x = {
  a: function(){
    return 3;
  },
  b: function(){
    return 4;
  }
};
y = {};
for (k in x) {
  v = x[k];
  console.log("key: ", k, "val: ", v);
  y[k] = fn$;
}
console.log("y is: ", y);
console.log("x's: ", x.a === x.b);
console.log("y's: ", y.a === y.b);
z = {};
z['a'] = function(){
  return x.a.call(this);
};
z['b'] = function(){
  return x.b.call(this);
};
console.log("z's: ", z.a === z.b);
function fn$(){
  return v.call(this);
}

打印:

x's:  false  # should be false, OK
y's:  true   # should be false, PROBLEM!
z's:  false  # should be false, OK

【问题讨论】:

  • 您将fn$ 分配给y 的所有属性,那么为什么y.ay.b 应该不同呢?您希望它们包含什么内容?
  • 如果你检查你的控制台,你可以看到y是一个带有a:function fn$()b:function fn$()的对象,所以比较返回true。
  • 我在发布问题后立即注意到fn$ 优化。谢谢...

标签: javascript loops livescript function-expression


【解决方案1】:

我不相信公认的自我回答。 v 引用仍然在变化。

你想要的是for let:

y = {}
for let k, v of x 
  console.log "key: ", k, "val: ", v 
  y[k] = -> v.call this 

【讨论】:

    【解决方案2】:

    问题的根源在于 Livescript 的 fn$ 优化。以下代码运行良好:

    Livescript:

    x = 
      a: -> 3 
      b: -> 4 
    
    y = {}
    for k, v of x 
      console.log "key: ", k, "val: ", v 
      y[k] = ``function (){return v.call(this)}``
    
    
    console.log "y is: ", y 
    console.log "x's: ", x.a is x.b   # should return false, returns false
    console.log "y's: ", y.a is y.b   # should return false, returns true
    
    z = {}
    z['a'] = -> 
      x.a.call this 
    
    z['b'] = -> 
      x.b.call this 
    
    console.log "z's: ", z.a is z.b  # should return false, returns false
    

    Javascript:

    var x, y, k, v, z;
    x = {
      a: function(){
        return 3;
      },
      b: function(){
        return 4;
      }
    };
    y = {};
    for (k in x) {
      v = x[k];
      console.log("key: ", k, "val: ", v);
      y[k] = function (){return v.call this};
    }
    console.log("y is: ", y);
    console.log("x's: ", x.a === x.b);
    console.log("y's: ", y.a === y.b);
    z = {};
    z['a'] = function(){
      return x.a.call(this);
    };
    z['b'] = function(){
      return x.b.call(this);
    };
    console.log("z's: ", z.a === z.b);
    

    【讨论】:

      猜你喜欢
      • 2017-08-21
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 2012-03-04
      • 1970-01-01
      相关资源
      最近更新 更多