admin管理员组文章数量:1391947
I was hoping someone could explain to me what's going on in the code below. I'm finding it very hard to wrap my head around why this closure is treating primitives and references differently. I'm hoping I'm missing something obvious here.
function returnFunction(x, y) {
return function() {
alert("x:" + x + " - nb of elements in y:" + y.length);
};
}
var f = 0;
var g = [];
var h = [];
for(var i = 0; i < 3; i++) {
f += 1;
g.push(i);
h.push(returnFunction(f, g));
}
for(var i = 0; i < 3; i++) {
h[i]();
}
// this is what gets returned
// x:1 - nb of elements in y: 3
// x:2 - nb of elements in y: 3
// x:3 - nb of elements in y: 3
// why do x and y get treated differently by js in this case?
I was hoping someone could explain to me what's going on in the code below. I'm finding it very hard to wrap my head around why this closure is treating primitives and references differently. I'm hoping I'm missing something obvious here.
function returnFunction(x, y) {
return function() {
alert("x:" + x + " - nb of elements in y:" + y.length);
};
}
var f = 0;
var g = [];
var h = [];
for(var i = 0; i < 3; i++) {
f += 1;
g.push(i);
h.push(returnFunction(f, g));
}
for(var i = 0; i < 3; i++) {
h[i]();
}
// this is what gets returned
// x:1 - nb of elements in y: 3
// x:2 - nb of elements in y: 3
// x:3 - nb of elements in y: 3
// why do x and y get treated differently by js in this case?
Share
Improve this question
asked Sep 26, 2015 at 18:06
ReckReck
8,7922 gold badges21 silver badges26 bronze badges
6 Answers
Reset to default 5This is because, The context was bound to the reference, not to the snapshot of the reference when it got called/created.
Let us walk through the code, block by block to have more clarity
for(var i = 0; i < 3; i++) {
f += 1;
g.push(i);
h.push(returnFunction(f, g));
}
The above loop executes 3 times, and each time it puts some value in g
array and in h
array.
So lets go inside, what the values are populated. Before that, be clear with this below code.
function returnFunction(x, y) {
return function() {
alert("x:" + x + " - nb of elements in y:" + y.length);
};
}
Calling above function once, will return a function, calling it again meaning whatever reference you received at first time, It will display an alert. In short (returnFunction(5,[4,5,6])())
will display an alert
"x:5 - nb of elements in y: 3"
. // It looks like the y
is taking an array argument, because in alert we have y.length property.
Value populated
loop_number:
1. - - - - f = 1 - - - - g = [1] - - - - h[return function when called with (1, array-g[1])]
2. - - - - f = 2 - - - - g = [1,2] - - - - h[return function when called with (1, array-g[1]), return function when called with (2, array-g[1,2])]
3. - - - - f = 3 - - - - g = [1,2,3] - - - - h[return function when called with (1, array-g[1]), return function when called with (2, array-g[1,2]), return function when called with (3, array-g[1,2,3])]
Finally
for(var i = 0; i < 3; i++) {
h[i]();
}
We are looping over h
array, i.e. values we had in array h
at loop-3 in the above explanation. It has inner function which already has the context values. i.e. it knows what is x
and what is y
when each time called.
Remember, the second parameter was an h
array reference we sent.
So if we execute those function like h[i]()
, it executes with first x's primary value and y
array reference. Even though when we are calling the returnFunction
with g
array and it had only one value, the returned function is bound with the reference, not at that snapshot what it had.
So the output is printing array size as // x:1 - nb of elements in y: 3
And the same goes on for 2nd and 3rd loop while executing returnFunction
.
Primitive types contain the actual data, while reference types contain only a memory address (a pointer to the memory location where the object's data resides).
So when you want to check the length
field of your array (which is a reference type) you first need to find what is the memory address where the object's data resides (you look into y
variable), you go to that address and finally you look at the data.
Now, when you call a function, for each parameter, a copy of their value is made and is stored in a local variable, available in your function scope. So every time you pass your array as a parameter, a copy of the memory address where the data resides is stored in a local variable (only the memory address is copied, not the whole object).
So, to answer your question: no, primitive and reference types are not treated differently when passed to a function. A copy is made in both cases, except the primitives contain the actual data, while references do not, they contain an address (a pointer to the actual data). When you follow the address you get the data, but the data might have been modified between the time you made a copy of the address and the time you checked the data.
the g
array is defined outside the scope of returnFunction
. Javascript is always pass by value. In the case of a reference, the reference itself is copied, but it's still the original array object, hence the final value it repeated 3 times.
That's because the inner function has only a reference to the array, and that array is altered before the function is called.
You can fix it by only accessing primitive values in the inner function.
function returnFunction(x, y) {
var len = y.length; // Primitive value
return function() {
alert("x:" + x + " - nb of elements in y:" + len);
};
}
Alternatively you can copy the array. Even if the original array is changed outside, the copy won't be altered.
function returnFunction(x, y) {
y = y.slice(); // Copy it
return function() {
alert("x:" + x + " - nb of elements in y:" + y.length);
};
}
It is because the closure holds the reference to the argument. The g array gets modified before the function is invoked. To avoid this, you would need to make a copy of the array that is passed in, and store it in the function.
The g array is modified 3 times and never copied. The primitives are passed by value and copied. Thus when the closure is defined, they keep the value from the previous loop. The last loop prints the lenght of the same array 3 times.
本文标签: Javascript closures primitive vs reference behaviourStack Overflow
版权声明:本文标题:Javascript closures: primitive vs reference behaviour - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744707161a2620908.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论