简体   繁体   中英

javascript setting objects equal

this is working the way I want, however I am a bit confused why it works.

I have two objects. set temp object equal to object A and manipulate temp object. Object A is affected.

set temp object equal to Object B (why aren't all three objects equal now?) I manipulate temp object. Object A is not affected.

 var tempObject = {}; var objectA = {A: 1}; var objectB = {A: 3}; $( document ).ready(function() { tempObject = objectA; add(tempObject); console.log(objectA); tempObject = objectB; add(tempObject); console.log(objectA); function add(arr){ arr.A += 1; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

When you deal with objects in JavaScript, it's always by-reference. It's kind of analogous to pointers in C/C++.

When you set tempObject to objectA , you are basically saying "tempObject now points to the same object as objectA". So, if you change a property of one, you change both.

When you then set tempObject to objectB , you are saying "tempObject now points to the same object as objectB". You aren't changing any of the objects with this, just which object tempObject is pointing to.

When you set tempObject to objectB , it ceases being a reference to objectA and now refers to objectB . Thus, when you make changes to tempObject , objectA is not affected, but objectB is.

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