我只是想检查一下我对 Javascript 中变量复制的理解。据我所知,变量是通过引用传递/分配的,除非您明确告诉它们使用 new 运算符创建副本。但当谈到使用闭包时我有点不确定。假设我有以下代码:
var myArray = [1, 5, 10, 15, 20];
var fnlist = [];
for (var i in myArray) {
var data = myArray[i];
fnlist.push(function() {
var x = data;
console.log(x);
});
}
fnlist[2](); // returns 20
我认为这是因为 fnlist[2]
仅在调用时查找 data
的值。所以我尝试了另一种方法:
var myArray = [1, 5, 10, 15, 20];
var fnlist = [];
for (var i in myArray) {
var data = myArray[i];
fnlist.push(function() {
var x = data;
return function() {
console.log(x);
}
}());
}
fnlist[2](); // returns 10
所以现在它返回“正确”的值。我是否可以说它有效,因为函数在调用时会将所有变量引用解析为其“常量”值?或者有更好的方法来解释吗?
任何有关此引用/复制业务的解释/解释链接也将不胜感激。谢谢!
I'd just like to check my understanding of variable copying in Javascript. From what I gather, variables are passed/assigned by reference unless you explicitly tell them to create a copy with the new
operator. But I'm a little uncertain when it comes to using closures. Say I have the following code:
var myArray = [1, 5, 10, 15, 20];
var fnlist = [];
for (var i in myArray) {
var data = myArray[i];
fnlist.push(function() {
var x = data;
console.log(x);
});
}
fnlist[2](); // returns 20
I gather that this is because fnlist[2]
only looks up the value of data
at the point where it is invoked. So I tried an alternative tack:
var myArray = [1, 5, 10, 15, 20];
var fnlist = [];
for (var i in myArray) {
var data = myArray[i];
fnlist.push(function() {
var x = data;
return function() {
console.log(x);
}
}());
}
fnlist[2](); // returns 10
So now it returns the 'correct' value. Am I right to say that it works because a function resolves all variable references to their 'constant' values when it is invoked? Or is there a better way to explain it?
Any explanations / links to explanations regarding this referencing / copying business would be appreciated as well. Thanks!
发布评论
评论(1)
闭包变量在其作用域结束时(即,当您离开定义闭包的函数时)绑定(“保存”在闭包中):
您找到的解决方案是完全正确的 - 您引入了另一个作用域并且强制闭包在该“内部”范围内绑定变量。
请参阅此处了解详细信息和说明。
Closure variables are bound ("saved" in the closure) at the moment when its scope ends, that is, when you leave the function where the closure is defined:
The solution you've found is perfectly correct - you introduce yet another scope and force closure to bind variables in that "inner" scope.
See here for details and explanations.