简体   繁体   中英

When I assign a variable to another variable does it not link them together?

I was trying to find out more about the lodash _.clone which I thought made a copy of the data in an object and created a different object. However when I was testing in the console I noticed this:

var a = 88
undefined
var b = a
undefined
console.log(b)
88 VM1010:2
undefined
var a = 100
undefined
console.log(b)
88 

What I was expecting to see was that b would be 100. Can someone explain this for me.

Update:

Here's the problem I had:

                $scope.grid.data = result;
                $scope.grid.backup = _.clone(result);

Here it appears that when I change a value inside the data object then a corresponding value changes inside the .backup object

That's how variables work in JavaScript, and most languages. Assignment of b = a assigns the value of variable a to variable b . In languages where you're able to set a variable as a reference to another variable, there is usually a specific syntax for doing so; JavaScript does not have this feature.

Note that this can appear confusing because, in the case of objects, the value being assigned from a to b is a reference to the object, but this still doesn't "link" the variables themselves, it just "points" them to the same object. Modifying either variable (via assignment) will not affect the other variable, but any changes the object through either variable will be mirrored by both variables because, again, they point to the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM