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

标签 javascript loops livescript function-expression

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

在 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

最佳答案

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

你想要的是for let:

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

关于javascript - for循环每次在Livescript中分配相同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39658320/

相关文章:

javascript - Swiper.js 自定义分页名称

javascript - 避免多次遍历数组以重新排列元素

postgresql - 遍历表并返回特定列

sections - 绑定(bind)访问运算符的一部分的语法是什么?

JavaScript 到 Livescript 的转换; js2ls 的问题?

javascript - Livescript:无法定义 AudioContext

javascript - 在javascript中更改所选文本的字体样式

javascript - 类型 'transformArticles' 上不存在属性 'typeof Article'

c - Summa C 程序崩溃

python在没有for循环的sql语句中列出list的值