2016-09-23 62 views
0
分配相同functon每次

我希望 “X的” 的结果, “Y的” 成果和 “z的” 结果是一样的:for循环的LiveScript

在为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 
+3

分配'FN $'到的所有属性'y'何必'y.a'和'y.b'有所不同呢?你期望他们包含什么? – JJJ

+1

如果你检查你的控制台,你可以看到'y'是一个带'a:function fn $()'和'b:function fn $()'的对象,所以比较返回true。 – Craicerjack

+1

在发布问题后,我注意到了'fn $'优化。谢谢... – ceremcem

回答

1

我不相信在接受自我的答案。 v引用仍然更改。

你想要什么,而不是为for let

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

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