JavaScript对象引用赋值后属性修改的行为原理问询
newObj Affects the Original obj in JavaScript Hey fellow dev! I totally get why this might be confusing—JavaScript's handling of objects vs. primitive values can trip up even experienced folks. Let's walk through exactly what's happening here step by step.
First, let's recap your code for clarity:
var obj = { prop1 : "12", prop2 : { prop3 : 24, prop4 : "mother" } }; newObj = obj; console.log(newObj); console.log(obj); newObj.prop2 = 1;
The Core Issue: References vs. Values
Here's the key thing to wrap your head around:
- Primitive values (like strings, numbers, booleans) are stored directly in the variable as their actual value. When you assign them to another variable, you make a full copy of the value—so changing one doesn't affect the other.
- Objects (and arrays, functions) work differently. When you create an object, JavaScript stores the object itself in the heap memory, and the variable (
objin your case) only holds a reference address pointing to that heap location.
What Happens in Your Code
- When you run
var obj = { ... }, JS creates the entire object structure in the heap. Theobjvariable doesn't contain the object—it contains a pointer to where the object lives in memory. - When you do
newObj = obj, you're not copying the object. You're copying the reference address fromobjtonewObj. Now bothobjandnewObjpoint to the exact same object in the heap. - So when you modify
newObj.prop2 = 1, you're usingnewObj's reference to access the shared object in the heap and update itsprop2property. Sinceobjpoints to that same object, checkingobj.prop2will show the updated value too.
To Create an Independent Copy
If you want newObj to be a separate object (so modifying it doesn't affect obj), you'll need to clone the original:
- For a shallow clone (works for your example, but won't deep-copy nested objects):
newObj = {...obj}; // Or newObj = Object.assign({}, obj); - For a deep clone (to handle nested objects like your
prop2):// Simple approach (has limitations with functions/symbols) newObj = JSON.parse(JSON.stringify(obj));
Quick Note on Execution Context
You mentioned the object becomes a property of the variable object in the execution context—this is correct! But that variable object stores the reference address to the heap object, not the object itself. So when newObj is assigned, it gets that same reference from the variable object's obj entry.
内容的提问来源于stack exchange,提问作者Deli Sandor

