1

I would expect "x's" results, "y's" results and "z's" results be the same:

In 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

In 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);
}

Prints:

x's:  false  # should be false, OK
y's:  true   # should be false, PROBLEM!
z's:  false  # should be false, OK
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
ceremcem
  • 3,900
  • 4
  • 28
  • 66
  • 3
    You assign `fn$` to all properties of `y` so why should `y.a` and `y.b` be different? What do you expect them to contain? – JJJ Sep 23 '16 at 10:24
  • 1
    if you check your console you can see `y` is an object with `a:function fn$()` and `b:function fn$()` so the comparison is returning true. – Craicerjack Sep 23 '16 at 10:24
  • 1
    I noticed the `fn$` optimization right after posting the question. Thank you... – ceremcem Sep 23 '16 at 10:29

2 Answers2

2

I don't believe in the accepted self-answer. The v reference still changes.

What you want instead is for let:

y = {}
for let k, v of x 
  console.log "key: ", k, "val: ", v 
  y[k] = -> v.call this 
Ven
  • 19,015
  • 2
  • 41
  • 61
1

Root of the problem was Livescript's fn$ optimization. Following code works well:

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);
ceremcem
  • 3,900
  • 4
  • 28
  • 66