1

我希望“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
4

2 回答 2

2

我不相信公认的自我回答。参考v仍然改变。

你想要的是for let

y = {}
for let k, v of x 
  console.log "key: ", k, "val: ", v 
  y[k] = -> v.call this 
于 2017-01-11T09:51:55.173 回答
1

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

现场脚本:

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);
于 2016-09-23T10:28:26.663 回答