You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript对象引用赋值后属性修改的行为原理问询

Why Modifying 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 (obj in your case) only holds a reference address pointing to that heap location.

What Happens in Your Code

  1. When you run var obj = { ... }, JS creates the entire object structure in the heap. The obj variable doesn't contain the object—it contains a pointer to where the object lives in memory.
  2. When you do newObj = obj, you're not copying the object. You're copying the reference address from obj to newObj. Now both obj and newObj point to the exact same object in the heap.
  3. So when you modify newObj.prop2 = 1, you're using newObj's reference to access the shared object in the heap and update its prop2 property. Since obj points to that same object, checking obj.prop2 will 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:46:33