I'm a newbie to js. Let me illustrate my question with a few examples.
Code 1
var temp = { key: "value" };
var data = ["v1", "v2"];
var result = [];
for (var i in data) {
var newdata = temp; /** Note here! **/
newdata.key = data[i];
result.push(newdata);
}
console.log(result);
// [ { key: 'v2' }, { key: 'v2' } ]
The result
here is unexpected.
Code 2
var temp = { key: "value" };
var data = ["v1", "v2"];
var result = [];
for (var i in data) {
var newdata = { key: "value" }; /* Note here! */
newdata.key = data[i];
result.push(newdata);
}
console.log(result);
// [ { key: 'v1' }, { key: 'v2' } ]
Now the result
is what I want.
It looks like the name binding operation in Python. But I googled a lot and could not get a satisfied answer. So I have to turn to stackoverflow for help.
My question:
Does JS have a name binding operation similar with Python? If not, why do these two piece of codes get different results?
[Edit]
I know about reference in C++, and name binding in Python. And I'm also aware of the differences between these two.
The only thing I was confused with was: In JS, is it reference or name binding? Or something else?
Thanks to all the comments, I totally understand it's similar with name binding rather than reference. (As I can't find any button to closed this question, I add the answer here.)