for循环在Livescript中每次都分配相同的功能

时间:2016-09-23 10:17:44

标签: javascript loops livescript function-expression

我希望" x' s"结果," y""结果和" 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

2 个答案:

答案 0 :(得分:2)

我不相信公认的自我回答。 v引用仍在更改。

您想要的是for let

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

答案 1 :(得分:1)

问题的根源是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);