Skip to content

Memory and 引用

理解如何 memory 工作 in programming: stack 对比. heap, 值对比. 引用, and 为什么它 causes subtle bugs.

你将学到

  • 如何 programs use memory 到存储数据
  • difference 之间 stack and heap memory
  • 值类型对比. 引用类型 and 为什么它 matters
  • 如何复制 and comparison behave differently for 每个
  • 常见 bugs caused 通过 unexpected 引用 sharing

概念讲解

Memory and References

Every variable in your program lives in memory — the computer's workspace for data. Understanding how memory is organized, and the difference between value types and reference types, explains some of the most confusing bugs beginners encounter. This is the lesson where "为什么做更改这个变量也更改那个 one?" finally makes sense.

Stack and Heap

Memory is divided into two regions:

  • The stack — fast, automatically managed, used for primitive values and function call frames. When you declare const x = 42, the value 42 goes on the stack. When a function returns, its stack frame is cleaned up automatically.
  • The heap — slower, manually or garbage-collector managed, used for objects and arrays. When you declare const obj = { name: "Ada" }, the object itself lives on the heap, and the variable obj on the stack holds a reference (a pointer) to that heap location.

Value Types (Primitives)

Primitives (string, number, boolean, null, undefined) are value types. When you assign a primitive to a new variable, the *value* is copied:

let a = 5;
let b = a;   // b gets a copy of the value 5
b = 10;      // changing b does not affect a
console.log(a);  // 5 (unchanged)

Each variable is independent. This is intuitive and safe — modifying one never affects the other.

Reference Types (Objects and Arrays)

Objects and arrays are reference types. When you assign an object to a new variable, the *reference* is copied, not the object itself. Both variables now point to the same object in memory:

const original = { count: 1 };
const copy = original;     // copy references the SAME object
copy.count = 99;           // modifying through copy...
console.log(original.count);  // 99 — original is also changed!

This is the #1 surprise for beginners. 复制 is not a copy of the object — it is a second label for the same object. Modifying through either variable affects both, because there is only one object.

Copying Objects

To create an actual copy of an object, you must explicitly copy its properties:

// Shallow copy (one level deep):
const shallow = { ...original };          // spread syntax
const arrCopy = [...array];               // array spread

// Deep copy (all levels) — for nested structures:
const deep = JSON.parse(JSON.stringify(original));

A shallow copy duplicates the top level but nested objects are still shared. A deep copy duplicates everything. Choose based on your data structure.

Comparison Behavior

Value and reference types also differ in comparison:

// Primitives compare by value:
console.log(5 === 5);              // true
console.log("hi" === "hi");        // true

// Objects compare by reference (identity):
console.log({} === {});            // false — different objects
const obj = {};
console.log(obj === obj);          // true — same reference

Two objects with identical contents are not equal with === because they are different objects in memory. Equality checks identity, not structural equality.

Why This Matters

Reference sharing causes real bugs: you modify a function parameter expecting it to be a local copy, but it is the caller's original object. You push to an array that is shared between two components, and both update unexpectedly. The defense is awareness: always know whether you are working with a value or a reference, and copy explicitly when you need independence.

示例代码

              // --- Value type: independent copies ---
let scoreA = 100;
let scoreB = scoreA;    // value copied
scoreB += 50;
console.log(scoreA, scoreB);  // 100 150 — independent

// --- Reference type: shared object ---
const playerA = { name: "Ada", score: 100 };
const playerB = playerA;       // reference copied, NOT the object
playerB.score += 50;
console.log(playerA.score);    // 150 — playerA also changed!

// --- Fix: create a real copy ---
const playerC = { ...playerA };  // shallow copy (new object)
playerC.score += 50;
console.log(playerA.score);      // 150 — playerA is safe now
console.log(playerC.score);      // 200

// --- Nested objects need deep copy ---
const config = { db: { host: "localhost", port: 5432 } };
const configCopy = { ...config };        // shallow — db is still shared!
configCopy.db.port = 3306;
console.log(config.db.port);             // 3306 — still shared!

const deepCopy = JSON.parse(JSON.stringify(config));
deepCopy.db.port = 1234;
console.log(config.db.port);             // 3306 — now independent

// --- Array reference sharing ---
const original = [1, 2, 3];
const ref = original;
ref.push(4);
console.log(original);  // [1, 2, 3, 4] — original changed!
const realCopy = [...original];
realCopy.push(5);
console.log(original);  // [1, 2, 3, 4] — original is safe
            

这个示例 demonstrates 值 independence, 引用 sharing, shallow 对比. deep 复制, and 数组引用 bugs. 每个小节 shows problem and fix — 模式你 将 encounter repeatedly in 真实 code.

动手试一试

  • JSON Formatter

    JSON serialization (used 通过 formatter) 创建 deep 复制的 数据. 粘贴 nested 对象 and see 如何结构是 preserved.

  • JSON Diff

    Diffing 对象通过值 (不引用) 是什么这个 tool 做. Two 对象使用相同内容 show 否 diff, 即使 {} === {} 是假.

常见错误

错误写法

Assigning 对象到 新变量 and expecting independent 复制.

正确做法

Use spread 语法 { ...obj } for shallow 复制, or JSON.parse(JSON.stringify(obj)) for deep 复制. 从不 assume assignment 复制对象 — 它仅 复制引用.

错误写法

Using === 到 compare two 对象使用相同内容 and expecting 真.

正确做法

=== compares 引用, 不内容. For deep equality, use 库函数 (如 lodash.isEqual) or compare 特定属性. JSON.stringify() === JSON.stringify(b) 工作 for 简单情况但 是 fragile.

错误写法

Mutating 对象通过 as 函数参数, surprising caller.

正确做法

If a function should not modify its input, work on a copy: const local = { ...input }. Or use immutable patterns — return a new object instead of modifying the input. This makes the function's behavior predictable.

相关速查表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误