w wyl123ly 的博客
MD

JavaScript-03-对象与原型链

57 KB 2026.10.11 原文件

JavaScript-03-对象与原型链

本篇讲什么

对象是 JavaScript 里唯一的复合数据结构(数组、函数、Map、Date 全都是对象),而原型链是它的继承机制。理解这两件事,才算是真正进入 JS 的中级阶段。

内容包括:对象字面量与属性访问、in 与 hasOwn、属性描述符、引用语义、浅拷贝与深拷贝(含循环引用)、__proto__ 与 prototype 的区别、属性查找过程、new 的四个步骤、instanceof 的原理、ES6 class 的全部要素(私有字段 #、静态成员、super)、Object.create 与原型式继承、组合继承与寄生组合继承的历史演进、Object.keys/values/entries/fromEntries、以及 JSON 序列化的六个局限。

读完后你应该能画出任意对象的原型链,并说清"为什么 ES6 的 class 只是语法糖"。


一、是什么:对象是"属性的集合",原型链是"查找的后备仓库"

对象(Object) 在规范里的定义非常朴素:它是一组属性的无序集合,每个属性有一个键(字符串或 Symbol)和一个属性描述符(描述这个属性的行为)。除此之外,每个对象还有一个内部槽 Prototype,指向另一个对象或 null——这就是原型链的入口。

一个对象的完整结构
┌──────────────────────────────────────────┐
│ 自有属性(own properties)                │
│   'name'  → { value: '张三', ... }        │
│   'age'   → { value: 28, ... }            │
├──────────────────────────────────────────┤
│ [[Prototype]] ──────────────┐            │
└─────────────────────────────┼────────────┘
                              ▼
                    Object.prototype(toString、hasOwnProperty…)
                              │ [[Prototype]]
                              ▼
                            null  ← 链条终点
概念含义怎么拿到
自有属性直接定义在这个对象上的属性Object.hasOwn(obj, key)
继承属性定义在原型链上某处的属性key in obj 为真但 hasOwn 为假
[[Prototype]]内部槽,指向原型对象Object.getPrototypeOf(obj)
prototype函数特有的属性,是"用它 new 出来的实例的原型"Fn.prototype
原型链由 [[Prototype]] 串起来的对象链条逐级 getPrototypeOf 直到 null

二、为什么这样设计

设计决策动机代价
对象是"动态字典"属性可随时增删,适合处理 JSON、配置、缓存拼错属性名不会报错,只得到 undefined
用原型链做继承不需要类声明就能共享方法;实例只存数据,方法挂在原型上省内存for...in 会遍历到继承属性;属性查找可能穿透整条链
class 只是语法糖老代码与库都基于原型,改成真正的类会破坏兼容类方法默认不可枚举、class 内部强制严格模式,和手写原型不完全等价
属性描述符可精细控制能实现只读字段、不可枚举的内部属性、getter/setterdefineProperty 默认全部为 false,忘记写会导致属性被写保护
赋值是"引用复制"避免大对象被隐式复制,性能可控改一个"以为已复制"的对象会污染原对象,是最高频的 bug
JSON 序列化只看可枚举自有属性简单、跨语言兼容函数、undefined、Symbol、循环引用、BigInt 都会出问题

一句话理解原型链

原型链就是"属性查找的失败重试链":访问 obj.x 时,先看 obj 自己有没有 x;没有就去 Object.getPrototypeOf(obj) 里找;再没有就继续往上;直到 null 才返回 undefined。写入则相反——永远只写自己(除非该属性是原型上的 setter)。


三、核心内容

3.1 对象字面量与属性访问

// ===== 可运行示例:字面量的全部写法 =====
'use strict';

const key = 'dynamicKey';
const user = {
  // ① 普通键值
  name: '张三',
  // ② 键可以不加引号(但含空格、连字符、以数字开头时必须加)
  'favorite-color': 'blue',
  1: '数字键会被转成字符串 "1"',
  // ③ 计算属性名(Computed Property Name):键由表达式动态算出
  [key]: 'reports',
  [`${key}Suffix`]: 'dynamicKeySuffix',
  // ④ 简写属性:变量名就是键名
  name2: '李四',
};

console.log(user['favorite-color']);   // 'blue'(含连字符的键只能用方括号)
console.log(user[key], user[1], user['1']); // 'reports' '数字键…' '数字键…'
console.log(user[`${key}Suffix`]);     // 'dynamicKeySuffix'

// ⑤ 方法简写与 getter
const counter = {
  value: 0,
  inc() { this.value++; return this.value; },       // 方法简写
  get doubled() { return this.value * 2; },          // getter:像属性一样读取
  set doubled(v) { this.value = Math.trunc(v / 2); },// setter:像属性一样赋值
};
counter.inc(); counter.inc();
console.log(counter.doubled);    // 4   (读 getter)
counter.doubled = 10;            // 触发 setter
console.log(counter.value);      // 5

点号 vs 方括号:

写法键的形式何时必须用
obj.name固定的标识符键名已知且是合法标识符时(首选,IDE 能自动补全)
obj['a-b']任意字符串键含特殊字符、以数字开头、键名是保留字时
obj[expr]表达式求值结果键存在变量里、需要拼字符串时
obj[Symbol()]Symbol想避免与字符串键撞名时

增删改查:

const o = { a: 1 };

// 查
console.log(o.a, o.b);                 // 1 undefined(不存在不报错)
o.b = 2;                               // 增/改:同一个语法
delete o.a;                            // 删:返回 boolean,删除失败(不可配置)返回 false
console.log('a' in o, o.a);            // false undefined

// 批量定义
Object.assign(o, { c: 3, d: 4 });
console.log(o);                        // { b: 2, c: 3, d: 4 }

// 复制一份便于对比(浅拷贝)
console.log({ ...o });                 // { b: 2, c: 3, d: 4 }

// 遍历自身的可枚举字符串键
for (const [k, v] of Object.entries(o)) console.log(k, '=', v);

3.2 in 与 hasOwn:自己的还是继承的?

判断方式是否看原型链是否看不可枚举属性是否看 Symbol 键备注
'x' in obj是是是最宽
Object.hasOwn(obj, 'x')否是是推荐(ES2022)
obj.hasOwnProperty('x')否是是有风险,见下方警告
Object.keys(obj)否否否只看可枚举字符串键
Object.getOwnPropertyNames(obj)否是否含不可枚举
Object.getOwnPropertySymbols(obj)否是只 Symbol
// ===== 可运行示例:三种判断的差异 =====
'use strict';

const proto = { inherited: '来自原型' };
const obj = Object.create(proto);          // obj 的原型是 proto
obj.own = '自己的';
Object.defineProperty(obj, 'hidden', { value: '不可枚举', enumerable: false });

console.log('inherited' in obj);            // true  ← in 会穿透原型链
console.log(Object.hasOwn(obj, 'inherited')); // false ← hasOwn 只认自己
console.log(Object.hasOwn(obj, 'own'));       // true
console.log(Object.keys(obj));                // ['own'] ← 不含不可枚举,也不含原型
console.log(Object.getOwnPropertyNames(obj)); // ['own', 'hidden']

// ⚠️ hasOwnProperty 的两个坑
// 坑一:对象自己定义了同名属性,方法被遮蔽
const shadowed = { hasOwnProperty: () => '我把它覆盖了' };
// shadowed.hasOwnProperty('x');   // 返回 '我把它覆盖了',逻辑失效
console.log(Object.hasOwn(shadowed, 'hasOwnProperty')); // true —— 用 Object.hasOwn 不受影响

// 坑二:Object.create(null) 造出的对象没有原型,也就没有 hasOwnProperty 方法
const bare = Object.create(null);
bare.k = 1;
// bare.hasOwnProperty('k');       // TypeError: bare.hasOwnProperty is not a function
console.log(Object.hasOwn(bare, 'k')); // true —— 它是静态方法,不依赖原型

3.3 属性描述符

每个属性都由一个描述符描述,分两类:

类别键说明
数据描述符value、writable有实际的值
访问器描述符get、set通过函数读写(两者不能同时出现在一个描述符里)
两类共有enumerable、configurable是否可被枚举 / 是否可被删除或改建
标志false 时的行为
writable赋值静默失败(严格模式抛 TypeError)
enumerable不出现在 for...in、Object.keys、展开运算符、JSON.stringify 里
configurable不能 delete,不能改标志位,且不能再改回 true
// ===== 可运行示例:defineProperty 的默认值全是 false =====
'use strict';

const config = {};
// 用 defineProperty 定义时,没写的标志位默认都是 false
Object.defineProperty(config, 'API_KEY', {
  value: 'abc123',
  writable: false,      // 只读
  enumerable: false,    // 不会被遍历/序列化
  configurable: false,  // 不能被删除或重新定义
});
// 注意:本文件开了 'use strict',所以写入只读属性会"抛错"而不是"静默失败";
// 非严格模式下这一行不会报错,但也改不掉值——两种模式下数据都是安全的。
try {
  config.API_KEY = 'hacked';
} catch (e) {
  console.log('写入只读属性被拒绝:', e.constructor.name); // TypeError
}
console.log(config.API_KEY);        // 'abc123' —— 没被改掉
console.log(Object.keys(config));   // [] —— 枚举不到
console.log(JSON.stringify(config));// '{}' —— 也序列化不出来
console.log(Object.getOwnPropertyDescriptor(config, 'API_KEY'));
// { value: 'abc123', writable: false, enumerable: false, configurable: false }

// 对比:字面量定义的属性,三个标志位默认都是 true
const normal = { x: 1 };
console.log(Object.getOwnPropertyDescriptor(normal, 'x'));
// { value: 1, writable: true, enumerable: true, configurable: true }

// ===== 实用场景一:用访问器做"校验 + 副作用" =====
const account = { _balance: 0 };
Object.defineProperty(account, 'balance', {
  get() { return this._balance; },
  set(v) {
    if (!Number.isFinite(v) || v < 0) throw new RangeError('余额必须是非负数');
    this._balance = v;
  },
  enumerable: true,
});
account.balance = 100;
console.log(account.balance);       // 100
try { account.balance = -1; } catch (e) { console.log(e.message); } // 余额必须是非负数

// ===== 实用场景二:批量设置标志位 =====
const settings = {};
Object.defineProperties(settings, {
  theme: { value: 'dark', enumerable: true, writable: true },
  version: { value: 3, enumerable: false },           // 内部字段,不许序列化
});
console.log(settings, Object.keys(settings));         // { theme: 'dark' } [ 'theme' ]

// ===== 冻结与密封 =====
const frozen = Object.freeze({ a: 1, nested: { b: 2 } });
try {
  frozen.a = 99;                     // 严格模式抛 TypeError;非严格模式静默失败
} catch (e) {
  console.log('冻结对象写入被拒绝:', e.constructor.name); // TypeError
}
frozen.nested.b = 99;                // ✅ 可以!freeze 是"浅冻结",嵌套对象没被冻结
console.log(frozen.a, frozen.nested.b); // 1 99

const sealed = Object.seal({ a: 1 });
sealed.a = 2;                        // ✅ 可以改值(seal 只禁止增删属性)
try {
  delete sealed.a;                   // ❌ 不能删属性
  sealed.b = 3;                      // ❌ 不能加新属性
} catch (e) {
  console.log('seal 后增删被拒绝:', e.constructor.name); // TypeError(严格模式)
}
console.log('seal 后:', sealed, Object.keys(sealed)); // seal 后: { a: 2 } [ 'a' ]

Object.freeze 是浅冻结

它只冻结第一层属性的描述符,嵌套对象依然可改(见上面的 nested.b)。要深冻结必须递归处理,或者干脆把数据设计成不可变结构(每次返回新对象)。

另一个陷阱:freeze 对 Map/Set/Date 的内容无效——它们的数据存在内部槽里,不是普通属性。

3.4 引用语义:赋值复制的是引用

// ===== 可运行示例:原始值 vs 对象,行为完全不同 =====
'use strict';

// 原始值:按"值"复制,两份互不影响
let a = 1;
let b = a;
b = 2;
console.log(a, b);                     // 1 2

// 对象:按"引用"复制,两份指向同一个对象
const o1 = { n: 1 };
const o2 = o1;
o2.n = 99;
console.log(o1.n);                     // 99 —— 改 o2 等于改 o1

// 函数参数传递也是"引用复制":传进去的是引用的副本
function mutate(obj) { obj.n = 0; }    // 能改到原对象的属性
function reassign(obj) { obj = { n: -1 }; }  // 只是让局部变量指向新对象,外部不受影响
const target = { n: 5 };
mutate(target);
console.log(target.n);                 // 0
reassign(target);
console.log(target.n);                 // 0 —— 没有变成 -1

// const 只锁绑定,不锁内容
const list = [1, 2];
list.push(3);                          // ✅ 合法:改的是对象内容
// list = [];                          // ❌ TypeError: Assignment to constant variable
console.log(list);                     // [1, 2, 3]

// 判等也是"引用相等"
console.log({} === {});                // false —— 两个不同的对象
const same = list;
console.log(same === list);            // true —— 同一个引用

心智模型:变量是"便签",对象是"储物柜"

const o2 = o1 不是复制储物柜,而是又贴了一张便签指向同一个柜子。想真正复制内容,必须显式做拷贝(下一节)。

3.5 浅拷贝与深拷贝

方法深度能拷贝 Symbol 键能拷贝不可枚举属性能处理循环引用能拷贝 Date/Map/Set能拷贝函数兼容性
Object.assign({}, o)浅是否会死循环/抛错只得到同引用只得到同引用很广
{ ...o }浅是否会死循环/抛错只得到同引用只得到同引用ES2018
手写 deepClone深看实现否需自己处理需自己处理通常同引用—
JSON.parse(JSON.stringify(o))深否否抛错丢失类型丢失很广
structuredClone(o)深否否支持支持抛 DataCloneErrorNode 17+ / 现代浏览器
// ===== 可运行示例:浅拷贝只复制第一层 =====
'use strict';

const original = {
  name: '订单A',
  amount: 100,
  buyer: { id: 1, name: '张三' },   // 嵌套对象
  tags: ['vip'],                     // 嵌套数组
};

const shallow1 = Object.assign({}, original);
const shallow2 = { ...original };

shallow1.name = '改过的名字';          // 第一层:互不影响
shallow1.buyer.name = '李四';          // 嵌套:互相影响!
console.log(original.name);            // '订单A' —— 第一层没被改
console.log(original.buyer.name);      // '李四'  ← 被改了,因为 buyer 是共享的引用
console.log(original.buyer === shallow2.buyer); // true —— 同一个对象

// ===== 深拷贝一:structuredClone(现代首选)=====
const deep = structuredClone(original);
deep.buyer.name = '王五';
deep.tags.push('new');
console.log(original.buyer.name, original.tags.length); // '李四' 1 —— 原对象未被污染

// 循环引用也能正确处理(这是 JSON 方案做不到的)
const circular = { name: 'root' };
circular.self = circular;
const clonedCircular = structuredClone(circular);   // 不抛错
clonedCircular.self.name = 'changed';
console.log(circular.name, clonedCircular.name);    // 'root' 'changed' —— 是两份独立对象
console.log(clonedCircular.self === clonedCircular); // true —— 内部引用关系被保留

// 类型也能保留(JSON 方案会全部变成字符串)
const typed = { when: new Date('2026-10-11T00:00:00Z'), ids: new Set([1, 2]), m: new Map([['k', 'v']]) };
const typedClone = structuredClone(typed);
console.log(typedClone.when instanceof Date, typedClone.ids instanceof Set, typedClone.m.get('k')); // true true 'v'

// 但函数不能被克隆:会抛 DataCloneError
try {
  structuredClone({ fn: () => 1 });
} catch (e) {
  console.log('克隆函数失败:', e.name);            // DataCloneError
}

// ===== 深拷贝二:JSON 方案的四个丢失点(完整清单见 3.12 节)=====
// 注意:这里故意不放 BigInt —— 一旦出现 BigInt,整句 JSON.stringify 会直接抛 TypeError,
// 后面的验证代码就跑不到了。BigInt 单独在后面演示。
const lossy = JSON.parse(JSON.stringify({
  fn: () => 1,        // 函数:整个键消失
  u: undefined,       // undefined:整个键消失
  d: new Date(0),     // Date:变成 ISO 字符串,不再是 Date 类型
  nan: NaN,           // NaN:变成 null
}));
console.log(Object.keys(lossy));       // [ 'd', 'nan' ] —— fn 和 u 都没了
console.log(typeof lossy.d, lossy.nan); // 'string' null —— 类型与值都被改写了

手写深拷贝(理解原理,生产环境优先用 structuredClone)

// ===== 可运行示例:一个能处理循环引用与常见内置类型的 deepClone =====
'use strict';

function deepClone(value, seen = new WeakMap()) {
  // ① 原始值、函数、null 直接返回(函数不复制,按引用共享)
  if (value === null || typeof value !== 'object') return value;

  // ② 循环引用:如果这个对象已经克隆过,直接复用之前的副本
  //    用 WeakMap 而不是普通对象,避免"记录克隆关系"本身造成内存泄漏
  if (seen.has(value)) return seen.get(value);

  // ③ 按类型分派。Object.prototype.toString 能可靠区分内置类型
  const tag = Object.prototype.toString.call(value);
  let result;

  if (tag === '[object Date]') return new Date(value.getTime());
  if (tag === '[object RegExp]') return new RegExp(value.source, value.flags);
  if (tag === '[object Map]') {
    result = new Map();
    seen.set(value, result);                       // 先登记,再递归,循环引用才安全
    for (const [k, v] of value) result.set(deepClone(k, seen), deepClone(v, seen));
    return result;
  }
  if (tag === '[object Set]') {
    result = new Set();
    seen.set(value, result);
    for (const v of value) result.add(deepClone(v, seen));
    return result;
  }

  // ④ 普通对象与数组:保留原型(用 Object.create 而不是字面量)
  result = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
  seen.set(value, result);

  // ⑤ 连 Symbol 键与不可枚举属性一起复制,比展开运算符更完整
  for (const key of Reflect.ownKeys(value)) {
    const desc = Object.getOwnPropertyDescriptor(value, key);
    if (desc.get || desc.set) {
      Object.defineProperty(result, key, desc);    // 访问器属性原样搬过去
    } else {
      Object.defineProperty(result, key, { ...desc, value: deepClone(value[key], seen) });
    }
  }
  return result;
}

const src = { n: 1, list: [1, { deep: true }], when: new Date(0), sm: new Set([1]) };
src.self = src;                                     // 制造循环引用
const copy = deepClone(src);
copy.list[1].deep = false;
console.log(src.list[1].deep, copy.list[1].deep);   // true false —— 深拷贝成功
console.log(copy.self === copy, copy.when instanceof Date); // true true
console.log(Object.keys(copy));                     // [ 'n', 'list', 'when', 'sm', 'self' ]

3.6 原型与原型链

// ===== 可运行示例:亲眼看到原型链 =====
'use strict';

const obj = { a: 1 };
const protoOfObj = Object.getPrototypeOf(obj);

console.log(protoOfObj === Object.prototype);          // true —— 字面量的原型就是 Object.prototype
console.log(Object.getPrototypeOf(Object.prototype));   // null —— 链的终点

// 逐级打印整条原型链
function chainOf(o) {
  const chain = [];
  let cur = o;
  while (cur !== null) {
    // 有 constructor 就显示它的名字,否则显示 null 原型
    chain.push(cur.constructor?.name ?? 'null 原型对象');
    cur = Object.getPrototypeOf(cur);
  }
  return chain.join(' → ') + ' → null';
}
console.log(chainOf({}));            // Object → null
console.log(chainOf([]));            // Array → Object → null
console.log(chainOf(() => {}));      // Function → Object → null
console.log(chainOf(Object.create(null))); // null 原型对象 → null

// 属性查找:逐级向上,找到即停
const parent = { shared: 'parent 的' };
const child = Object.create(parent);
child.own2 = 'child 的';
console.log(child.own2, child.shared);          // 'child 的' 'parent 的'(来自原型)
console.log(Object.hasOwn(child, 'shared'));    // false —— 不在自己身上

// 写入永远写自己:这叫"遮蔽(shadowing)"
child.shared = 'child 覆盖的';                   // 在 child 上新建一个 own 属性
console.log(child.shared, parent.shared);        // 'child 覆盖的' 'parent 的' —— parent 没被改
console.log(Object.hasOwn(child, 'shared'));     // true

// delete 只能删自己的属性:删完就"露出"原型上的值
delete child.shared;
console.log(child.shared);                       // 'parent 的' —— 原型上的又可见了

__proto__ 与 prototype 的区别(最高频的混淆点)

表达式是什么属于谁用途
obj.__proto__[[Prototype]] 的访问器(历史遗留,是 Object.prototype 上的 getter/setter)所有对象读写"我的原型是谁"
Fn.prototype一个普通属性,值是对象只有函数有决定"用 new Fn() 造出来的实例的原型是谁"
Object.getPrototypeOf(obj)标准的读原型方式—推荐,替代 __proto__
Object.setPrototypeOf(obj, p)标准的写原型方式—性能差(会破坏引擎的内联缓存),尽量在创建时就确定
Fn.prototype.constructor指回 Fn 自身函数原型对象让实例能反查构造函数
// ===== 可运行示例:三者的关系 =====
'use strict';

function Person(name) { this.name = name; }
Person.prototype.say = function () { return `我是 ${this.name}`; };

const p = new Person('小明');

console.log(p.__proto__ === Person.prototype);           // true  ← 实例的原型是构造函数的 prototype
console.log(Person.prototype.constructor === Person);    // true  ← 反向指回
console.log(Person.__proto__ === Function.prototype);    // true  ← 函数自己也是对象,它的原型是 Function.prototype
console.log(Object.getPrototypeOf(Person.prototype) === Object.prototype); // true
console.log(p.say());                                    // '我是 小明'

// ⚠️ __proto__ 本身来自 Object.prototype,所以"没有原型"的对象上没有它
const bare = Object.create(null);
console.log('__proto__' in bare);                        // false —— 属性根本不存在
console.log(bare.__proto__);                             // undefined(访问不存在的属性)
console.log(Object.getPrototypeOf(bare));                // null —— 这才是"真正的没有原型"

原型链的三个坑

1. 原型上的属性是被所有实例共享的。如果原型上放的是对象/数组,一个实例改它,所有实例都跟着变:

```js

function Bad() {}

Bad.prototype.list = []; // ❌ 所有实例共享同一个数组

const x = new Bad(); const y = new Bad();

x.list.push(1);

console.log(y.list); // [1] —— y 也被"污染"了

// 正确做法:在构造函数里初始化实例级数据 this.list = []

```

2. for...in 会遍历继承来的可枚举属性(见 JavaScript-01-基础语法与类型 3.10 节)。

3. 改了 prototype 会丢 constructor:Person.prototype = { say() {} } 之后 p.constructor 不再是 Person,需要手动补 constructor: Person。

3.7 构造函数与 new 的四个步骤

new Fn(...args) 到底做了什么?

步骤动作规范中的说法
①创建一个新对象,其 [[Prototype]] 指向 Fn.prototypeOrdinaryCreateFromConstructor
②把这个新对象作为 this,执行 Fn 的函数体[[Construct]] 调用函数体
③如果函数体返回的是对象,就用它替换新对象;否则忽略返回值返回值的处理规则
④返回最终对象—
// ===== 可运行示例:用三步手写 new,验证理解 =====
'use strict';

function myNew(Ctor, ...args) {
  // ① 创建一个对象,原型指向构造函数的 prototype
  //    用 Object.create 而不是 {},因为 {} 的原型是 Object.prototype,不对
  const obj = Object.create(Ctor.prototype);
  // ② 用这个对象当 this 执行构造函数,拿到返回值
  const result = Ctor.apply(obj, args);
  // ③ 如果构造函数返回了对象,就以它为准(这是规范规定的行为)
  return (result !== null && (typeof result === 'object' || typeof result === 'function'))
    ? result
    : obj;
}

function User(name, age) {
  this.name = name;
  this.age = age;
  // 注意:这里没有 return,所以返回的是新建的 this
}
User.prototype.greet = function () { return `${this.name}(${this.age})`; };

const u1 = new User('张三', 28);
const u2 = myNew(User, '张三', 28);
console.log(u1.greet(), u2.greet());                 // '张三(28)' '张三(28)'
console.log(u1 instanceof User, u2 instanceof User); // true true —— 手写的也能过 instanceof

// ④ 构造函数返回对象的"特殊"行为
function ReturnsObject() {
  this.ignored = true;
  return { replaced: true };          // 返回对象 → 实例被替换
}
console.log(new ReturnsObject());     // { replaced: true }

function ReturnsPrimitive() {
  this.kept = true;
  return 42;                          // 返回原始值 → 被忽略
}
console.log(new ReturnsPrimitive());  // ReturnsPrimitive { kept: true }

// ⑤ 忘记 new 会怎样:this 变成 undefined(严格模式),属性写不上去
try {
  // @ts-expect-error 故意演示错误用法
  User('李四', 30);
} catch (e) {
  console.log('忘记 new:', e.constructor.name);      // TypeError
}
// 防御写法:用 new.target 检测是否被 new 调用
function Safe(name) {
  if (!new.target) return new Safe(name);            // 没 new 就自己补一个
  this.name = name;
}
console.log(Safe('王五').name);                      // '王五' —— 不加 new 也能用

3.8 instanceof 的原理

a instanceof B 检查的是:B.prototype 是否出现在 a 的原型链上。它和"a 是谁造出来的"无关——a 可以被任意方式创建,只要原型链对得上。

// ===== 可运行示例:手写 instanceof,理解它的本质 =====
'use strict';

function myInstanceOf(obj, Ctor) {
  const target = Ctor.prototype;                 // 要找的目标
  let cur = Object.getPrototypeOf(obj);          // 从 obj 的原型开始
  while (cur !== null) {
    if (cur === target) return true;             // 链上出现了目标 prototype
    cur = Object.getPrototypeOf(cur);            // 继续往上
  }
  return false;
}

class Animal {}
class Dog extends Animal {}
const d = new Dog();

console.log(myInstanceOf(d, Dog), myInstanceOf(d, Animal), myInstanceOf(d, Object));
// true true true —— 子类实例同时是父类和 Object 的实例
console.log(d instanceof Dog, d instanceof Animal, d instanceof Object); // true true true
console.log(myInstanceOf(d, Array));             // false

// 关键:instanceof 只看原型链,不看"谁造的"
const fake = Object.create(Dog.prototype);       // 从没调用过 Dog 的构造函数
console.log(fake instanceof Dog);                // true
console.log(Object.hasOwn(fake, 'anything'));    // false —— 它其实什么都没有

// instanceof 的三个失效场景
console.log('abc' instanceof String);            // false —— 原始值不是对象
console.log('abc' instanceof Object);            // false
console.log(new String('abc') instanceof String);// true  —— 包装对象才是对象
// 跨窗口/跨 realm(如 iframe)时,Array 构造函数不是同一个 → 数组判断失效
console.log(Array.isArray([1, 2]));              // true —— 所以判数组永远用 Array.isArray

instanceof vs typeof vs Object.prototype.toString

- 判原始类型:typeof(注意 null 与数组的坑)。

- 判数组:Array.isArray()(跨 realm 也可靠)。

- 判某个类的实例 / 继承关系:instanceof(但要求对象在同一 realm,且原型链没被篡改)。

- 想拿精确的内置类型名:Object.prototype.toString.call(x),例如 '[object Date]'。

3.9 ES6 class:语法糖,但有真实差别

// ===== 可运行示例:class 的全部要素 =====
'use strict';

class Shape {
  // ① 静态字段:属于类本身,不属于实例
  static count = 0;
  static #registry = [];                       // 静态私有字段

  // ② 实例字段:每个实例一份,在构造函数体执行前初始化
  name = '未命名图形';
  #secret = '这是私有字段';                     // ③ 私有字段:只能在本类内部访问

  // ④ 构造函数
  constructor(name) {
    this.name = name;
    Shape.count++;                             // 统计创建了几个实例
    Shape.#registry.push(name);
  }

  // ⑤ 实例方法:挂在 Shape.prototype 上,所有实例共享(省内存)
  area() { return 0; }

  // ⑥ 访问器
  get label() { return `[${this.name}]`; }
  set label(v) {
    if (typeof v !== 'string' || v.length === 0) throw new TypeError('label 必须是非空字符串');
    this.name = v;
  }

  // ⑦ 私有方法
  #reveal() { return this.#secret; }
  // 公有方法可以调用私有方法,外部拿不到 #secret
  describe() { return `${this.label} 面积=${this.area()} 内部=${this.#reveal()}`; }

  // ⑧ 静态方法
  static list() { return [...Shape.#registry]; }   // 返回副本,防止外部改到内部数组

  // ⑨ 静态初始化块(ES2022):适合做"类加载时的一次性初始化",
  //    它的执行时机在所有静态字段初始化之后,且能访问私有字段
  static CONFIG;
  static {
    Shape.CONFIG = Object.freeze({ maxArea: 10000, units: Object.freeze(['px', 'cm']) });
  }
}

class Circle extends Shape {
  // 子类字段在 super() 之后初始化
  radius;

  constructor(radius) {
    super('圆');             // ⑩ 必须先调用 super 才能用 this
    this.radius = radius;
  }

  area() { return Math.PI * this.radius ** 2; }    // 覆盖父类方法

  get label() { return `圆形(${this.radius})`; }   // 覆盖访问器

  describe() {
    return `${super.describe()} | 半径=${this.radius}`; // ⑪ super 调用父类方法
  }

  static create(r) { return new Circle(r); }       // 静态方法也会被继承
}

const c = new Circle(2);
console.log(c.describe());                 // 圆形(2) 面积=12.566370614359172 内部=这是私有字段 | 半径=2
console.log(Shape.count);                  // 1
console.log(Circle.list());                // [ '圆' ] —— 静态方法可从子类调用
console.log(typeof Shape);                 // 'function' —— class 本质就是函数

// 私有字段真的访问不到
// console.log(c.#secret);                 // SyntaxError(类外写 #secret 直接语法错误)
console.log(Object.keys(c));               // [ 'name', 'radius' ] —— 私有字段不出现在这里
console.log(c instanceof Circle, c instanceof Shape); // true true

// 静态初始化块的产物:一个被冻结的类级配置(两层都冻结,才是真的不可改)
console.log(Object.isFrozen(Shape.CONFIG.units), Shape.CONFIG.maxArea); // true 10000

class 与手写原型的三个真实差别(所以"只是语法糖"这句话并不完全准确):

差别class手写构造函数 + 原型
调用方式必须 new,直接调用抛 TypeError可以直接调用(this 会是 undefined 或全局对象)
严格模式类内部始终严格模式取决于所在脚本
方法与原型属性方法不可枚举(enumerable: false)通过赋值添加的方法可枚举
提升有 TDZ,声明前不可用函数声明会提升
私有字段支持 #无原生支持,只能靠闭包或 WeakMap 模拟
// ===== 验证"方法不可枚举"这一差别 =====
class A { m() {} }
function B() {}
B.prototype.m = function () {};

console.log(Object.keys(A.prototype));    // []          —— class 方法不可枚举
console.log(Object.keys(B.prototype));    // [ 'm' ]     —— 赋值方式可枚举
console.log(Object.getOwnPropertyDescriptor(A.prototype, 'm').enumerable); // false

// 这也意味着:class 实例的 JSON 序列化不会被方法干扰,但 for...in 也不会看到方法
console.log(JSON.stringify(new A()));     // '{}'

class 的四个易错点

1. super 必须在 this 之前:子类构造函数里访问 this 之前一定要先 super(),否则抛 ReferenceError。

2. 方法丢失 this:const f = c.describe; f() 会抛 TypeError(类内部严格模式)。解决:bind、箭头函数字段(describe = () => {})、或调用时保持 c.describe()。

3. class 字段箭头函数 vs 原型方法:method = () => {} 是每个实例一份(更占内存),但天然绑定 this;method() {} 挂在原型上共享,但会丢 this。React 类组件时代这个取舍很常见。

4. 不要用 class 存共享可变数据:静态字段是所有实例共享的,static cache = [] 是全局状态,测试之间会互相污染。

3.10 Object.create 与原型式继承

// ===== 可运行示例:Object.create 的三种用法 =====
'use strict';

// 用法一:直接指定原型(最"原型式"的继承写法)
const base = {
  greet() { return `你好,我是 ${this.name}`; },
};
const derived = Object.create(base);
derived.name = '小明';
console.log(derived.greet());                   // '你好,我是 小明'
console.log(Object.hasOwn(derived, 'greet'));   // false —— greet 来自原型

// 用法二:创建"没有原型"的纯字典
// 适合做缓存/映射表:不会误取到 toString、constructor 这些继承属性,
// 也不会因为原型链被污染而出现意料之外的键(原型污染攻击的防护手段之一)
const dict = Object.create(null);
dict.lang = 'js';                              // 普通键,和普通对象没区别
console.log(dict.lang, Object.getPrototypeOf(dict)); // 'js' null
// 想存 "__proto__" 这个字符串键时,null 原型字典也不会触发"改原型"的魔法
dict['__proto__'] = 'no magic here';           // 真的只是加了一个普通属性
console.log(dict['__proto__'], Object.getPrototypeOf(dict)); // 'no magic here' null
// 对比:普通对象上给 __proto__ 赋值会改原型,而不是新增属性
const normalObj = {};
normalObj['__proto__'] = { polluted: true };   // ❌ 改的是原型!
console.log(Object.getPrototypeOf(normalObj).polluted, Object.hasOwn(normalObj, '__proto__')); // true false

// 用法三:同时定义属性描述符(第二个参数)
const user = Object.create(base, {
  name: { value: '李四', enumerable: true, writable: true },
  id: { value: 1, enumerable: false },           // 内部字段,不参与遍历
});
console.log(user.greet(), Object.keys(user));    // '你好,我是 李四' [ 'name' ]

// ===== 历史演进:四种继承写法 =====
// ① 原型链继承:把子类 prototype 指向父类实例 —— 缺点:父类属性被所有子类实例共享
function ParentA(name) { this.name = name; this.tags = []; }
ParentA.prototype.hi = function () { return this.name; };
function ChildA() {}
ChildA.prototype = new ParentA('默认');          // ❌ 无法给每个实例传不同参数
const ca1 = new ChildA(); const ca2 = new ChildA();
ca1.tags.push('x');
console.log('① 原型链继承共享问题:', ca2.tags);   // [ 'x' ] —— 被污染

// ② 构造函数继承:在子类里调用父类构造函数 —— 缺点:拿不到父类原型上的方法
function ChildB(name) { ParentA.call(this, name); }
const cb = new ChildB('小刚');
console.log('② 构造函数继承:', cb.name, typeof cb.hi); // '小刚' 'undefined' —— 方法丢了

// ③ 组合继承(过去的主流写法):构造函数 + 原型链,两者结合
function ChildC(name) { ParentA.call(this, name); }        // 继承实例属性
ChildC.prototype = Object.create(ParentA.prototype);       // 继承原型方法
ChildC.prototype.constructor = ChildC;                     // 修复被覆盖的 constructor
const cc = new ChildC('小美');
console.log('③ 组合继承:', cc.name, cc.hi(), cc instanceof ParentA); // '小美' '小美' true

// ④ 寄生组合继承:组合继承的优化版 —— 父类构造函数只被调用一次,不产生多余属性
function ChildD(name) { ParentA.call(this, name); }
ChildD.prototype = Object.create(ParentA.prototype, {
  constructor: { value: ChildD, writable: true, configurable: true }, // 一次定义到位
});
const cd = new ChildD('小强');
console.log('④ 寄生组合继承:', cd.name, cd.hi(), Object.hasOwn(cd, 'tags')); // '小强' '小强' true

// 现代写法:这些历史包袱都用 class + extends 一行解决,但理解它们才知道 class 在做什么
class ChildE extends ParentA {
  constructor(name) { super(name); }
}
console.log('⑤ class extends:', new ChildE('小华').hi());  // '小华'

为什么还要了解这四种继承

① 读懂老项目的代码(jQuery 时代、早期 ES5 库全是这些模式);

② 面试与源码阅读的常见话题;

③ Object.create 本身仍在用——尤其是创建 null 原型字典与实现极简的委托模式。

3.11 对象的遍历与转换

API返回是否含不可枚举是否含 Symbol是否含原型链
Object.keys(o)键数组否否否
Object.values(o)值数组否否否
Object.entries(o)[键, 值] 数组否否否
Object.fromEntries(iter)新对象—支持—
for...in键否否是
Reflect.ownKeys(o)键数组是是否
// ===== 可运行示例:遍历与转换的实用组合 =====
'use strict';

const scores = { 语文: 90, 数学: 85, 英语: 78 };
const sym = Symbol('hidden');
const withHidden = { ...scores, [sym]: 'symbol 值', internal: '不可枚举' };
Object.defineProperty(withHidden, 'internal', { value: '不可枚举', enumerable: false });

console.log(Object.keys(scores));                  // [ '语文', '数学', '英语' ]
console.log(Object.values(scores));                // [ 90, 85, 78 ]
console.log(Object.entries(scores));               // [ ['语文',90], ['数学',85], ['英语',78] ]
console.log(Object.keys(withHidden));              // 不含 symbol 与 internal
console.log(Reflect.ownKeys(withHidden));          // 含 'internal' 与 Symbol(hidden)

// ① 对象 → 数组(便于用数组方法)
const entries = Object.entries(scores);
const passed = entries.filter(([, v]) => v >= 80);       // 用逗号跳过键:[, v]
console.log(passed.map(([k]) => k));                     // [ '语文', '数学' ]

// ② 数组 → 对象
console.log(Object.fromEntries([['a', 1], ['b', 2]]));   // { a: 1, b: 2 }

// ③ 对象 → 变换后的对象(mapValues 模式)
const curved = Object.fromEntries(
  Object.entries(scores).map(([k, v]) => [k, Math.round(Math.sqrt(v) * 10) / 10]),
);
console.log(curved);                               // { 语文: 9.5, 数学: 9.2, 英语: 8.8 }

// ④ Map ↔ 对象互转(fromEntries 接受任何可迭代的键值对)
const map = new Map([['x', 1], ['y', 2]]);
const objFromMap = Object.fromEntries(map);
console.log(objFromMap);                           // { x: 1, y: 2 }
console.log(new Map(Object.entries(objFromMap)));  // Map(2) { 'x' => 1, 'y' => 2 }

// ⑤ 求和/求最大值:用 entries 而不是 for...in
const total = Object.values(scores).reduce((a, b) => a + b, 0);
const best = Object.entries(scores).reduce((acc, [k, v]) => (v > acc[1] ? [k, v] : acc), ['', -Infinity]);
console.log(total, best);                          // 253 [ '语文', 90 ]

// ⑥ 键的顺序规则:整数键(按升序)排在最前,其余字符串键按插入顺序,Symbol 最后
const ordered = { b: 1, 2: 'two', a: 2, 1: 'one' };
console.log(Object.keys(ordered));                 // [ '1', '2', 'b', 'a' ]

3.12 JSON 序列化的六个局限

JSON.stringify 只处理可枚举的自有字符串键属性,并且只认识 JSON 支持的六种值类型(对象、数组、字符串、数字、布尔、null)。

输入JSON.stringify 的行为
函数 / undefined(在对象里)该属性被整个丢弃
函数 / undefined(在数组里)变成 null(为了保持数组长度)
Symbol 键的属性被忽略
BigInt抛 TypeError
NaN / Infinity变成 null
Date变成 ISO 字符串(丢失类型)
Map / Set / RegExp / Error变成 {}(RegExp 是 {},Error 也是 {})
循环引用抛 TypeError: Converting circular structure to JSON
顶层 undefined / 函数JSON.stringify(x) 返回 undefined(不是字符串!)
稀疏数组的空洞变成 null
原型上的属性不序列化(只处理自有属性)
// ===== 可运行示例:六个局限逐个复现 =====
'use strict';

const source = {
  str: '文本',
  num: 1,
  bool: true,
  nil: null,
  fn: () => 1,                     // ① 函数 → 键消失
  undef: undefined,                // ② undefined → 键消失
  [Symbol('s')]: 'symbol 键',      // ③ Symbol 键 → 忽略
  nan: NaN,                        // ④ NaN → null
  inf: Infinity,                   // ④ Infinity → null
  when: new Date('2026-10-11T00:00:00Z'), // ⑤ Date → 字符串
  map: new Map([['k', 'v']]),      // ⑥ Map → {}
  set: new Set([1, 2]),            // ⑥ Set → {}
  arr: [1, undefined, () => {}],   // 数组里的 undefined/函数 → null
};
console.log(JSON.stringify(source));
// {"str":"文本","num":1,"bool":true,"nil":null,"nan":null,"inf":null,
//  "when":"2026-10-11T00:00:00.000Z","map":{},"set":{},"arr":[1,null,null]}

// BigInt 直接抛错
try {
  JSON.stringify({ big: 10n });
} catch (e) {
  console.log('BigInt:', e.constructor.name);        // TypeError
}
// 兜底方案:给 BigInt 加 toJSON,序列化成字符串(避免丢精度)
BigInt.prototype.toJSON = function () { return this.toString(); };
console.log(JSON.stringify({ big: 1234567890123456789n })); // {"big":"1234567890123456789"}

// 循环引用抛错
const circular = { name: 'a' };
circular.self = circular;
try {
  JSON.stringify(circular);
} catch (e) {
  console.log('循环引用:', e.message.slice(0, 40));  // Converting circular structure to JSON
}

// 顶层是函数/undefined 时返回 undefined(不是字符串)
console.log(JSON.stringify(undefined), JSON.stringify(() => 1)); // undefined undefined

// ===== 三个进阶技巧 =====
// 技巧一:replacer 数组做"白名单",只序列化需要的字段(也是脱敏手段)
const user = { id: 1, name: '张三', password: 'secret', token: 'abc' };
console.log(JSON.stringify(user, ['id', 'name']));   // {"id":1,"name":"张三"}

// 技巧二:replacer 函数做精细处理(去掉密码、格式化数字)
const safeJson = JSON.stringify(user, (key, value) => {
  if (key === 'password' || key === 'token') return undefined;  // 返回 undefined 即丢弃
  if (typeof value === 'number') return Number(value.toFixed(2));
  return value;
});
console.log(safeJson);                                // {"id":1,"name":"张三"}

// 技巧三:toJSON —— 让对象自己决定怎么被序列化
class Money {
  constructor(cents) { this.cents = cents; }
  toJSON() { return { amount: this.cents / 100, currency: 'CNY' }; } // 对外暴露"元"
}
console.log(JSON.stringify({ price: new Money(1999) })); // {"price":{"amount":19.99,"currency":"CNY"}}

// 反序列化的局限:Date 变回字符串,需要手动"复活"
const raw = '{"when":"2026-10-11T00:00:00.000Z"}';
const parsed = JSON.parse(raw);
console.log(typeof parsed.when);                      // 'string' —— 不再是 Date
const revived = JSON.parse(raw, (key, value) =>
  (key === 'when' ? new Date(value) : value));        // reviver 是复活的唯一接口
console.log(revived.when instanceof Date);            // true

生产环境的三个 JSON 事故

1. undefined 属性消失导致接口字段缺失:前端依赖 data.field !== undefined 判断,结果键根本不存在 → 用 null 占位,或在序列化前补齐字段。

2. 循环引用让整个接口 500:ORM 查出的实体带双向关联(article.author / author.articles)→ 序列化前用 DTO 挑字段,别直接把实体丢给 JSON.stringify。

3. BigInt 直接抛错:数据库 BIGINT 主键在 Node 18+ 的某些驱动里会返回 BigInt → 统一转成字符串(见 JavaScript-01-基础语法与类型 3.5 节的精度问题)。

该用哪种拷贝/持久化方案

- 只读配置、浅层数据 → 展开运算符 { ...o }。

- 深层数据、含 Date/Map/Set/循环引用 → structuredClone(现代首选)。

- 要跨语言传输、要落库 → JSON,但要清楚它会丢什么。

- 要保留函数、要完全掌控 → 手写 deepClone(如 3.5 节)或使用成熟的工具库。


四、注意事项与常见坑

对象与原型链的十个高频陷阱

1. 展开运算符只做浅拷贝,嵌套对象依然共享引用。

2. Object.assign 会触发 setter、defineProperty 不会——目标对象上的 setter 会被调用,可能产生意外副作用。

3. Object.freeze 是浅冻结,且对 Map/Set/Date 内容无效。

4. delete 影响性能:会让引擎把对象从"快速模式"降级为字典模式,热点对象别频繁删属性,用 null 占位代替。

5. 原型上放可变对象会被所有实例共享(Fn.prototype.list = [] 是经典事故)。

6. __proto__ 是访问器不是数据属性,直接给它赋值会改原型,用 Object.getPrototypeOf / Object.create 更安全。

7. hasOwnProperty 可被同名属性遮蔽,统一用 Object.hasOwn(obj, k)。

8. class 方法默认不可枚举且强制严格模式,与手写原型不完全等价。

9. instanceof 跨 iframe/跨 realm 会失效,判数组用 Array.isArray。

10. JSON.parse(JSON.stringify(x)) 不是通用深拷贝,会丢类型、丢函数、遇循环引用抛错。

三个静默出错、排查成本极高的场景

- 改到别人的数据:函数内部直接改传入的对象(items.forEach(i => i.price *= 0.9)),调用方数据被污染。约定:参数只读,要改就返回新对象。

- 共享原型状态:原型上的数组/对象被一个实例改了,所有实例跟着变。

- 原型污染(Prototype Pollution):把用户输入当键名做深合并时,__proto__、constructor.prototype 这类键会改到 Object.prototype,影响全程序。防护:合并前过滤这些键,或用 Object.create(null) 做容器。


五、练习题

练习 1(自有 vs 继承)

给定 const o = Object.create({ inherited: 1 }); o.own = 2;,分别写出 'inherited' in o、Object.hasOwn(o, 'inherited')、Object.keys(o)、Reflect.ownKeys(o) 的结果,并解释每一行的判据。

练习 2(深拷贝判断)

下面哪些场景可以用 { ...obj },哪些必须用 structuredClone?① 只读的配置对象,值全是字符串;② 表单数据,含嵌套的地址对象;③ 含 Date 与 Map 的缓存快照;④ 需要脱敏(去掉 password 字段)的接口返回;⑤ 带双向关联的 ORM 实体。

练习 3(手写 new)

不看本篇的代码,自己实现 myNew(Ctor, ...args),要求:① 实例能通过 instanceof;② 构造函数返回对象时以返回值为准;③ 构造函数返回原始值时忽略。然后用 new.target 写一个"忘记 new 也能工作"的构造函数。

练习 4(原型链与 class)

用 class 写 Shape / Rectangle / Square 三层继承,要求:① area() 与 perimeter() 在子类实现;② Square 固定宽高相等;③ 用静态方法 Shape.create(type, ...args) 做工厂;④ 用一个 #id 私有字段保证每个实例 ID 唯一且不可被外部修改。画出 new Square(3) 的完整原型链。

练习 5(JSON 安全序列化)

写一个 toSafeJson(entity),要求:① 丢弃 password/token 字段;② 把 BigInt 转成字符串;③ 把 Date 转成 ISO 字符串;④ 遇到循环引用不抛错(提示:用 WeakSet 记录已访问对象,遇到重复时输出 '[Circular]');⑤ 用 JSON.stringify(value, replacer, 2) 输出缩进。


六、常见问题 FAQ

class 到底是不是语法糖?

基本是,但有三处硬差别:① 必须用 new 调用;② 类体内部始终是严格模式;③ 原型上的方法是不可枚举的。除此之外,extends 的实质就是设置两条原型链(Child.prototype.__proto__ = Parent.prototype 与 Child.__proto__ = Parent,后者让静态方法可继承)。理解原型链之后,class 的每个行为都能推导出来。

我该用 class 还是工厂函数?

判据是"要不要共享方法 + 要不要 instanceof"。大量实例 + 需要共享方法省内存 + 需要 instanceof/extends → class。只有一两个对象 + 需要闭包私有状态 + 更在意可组合性 → 工厂函数(返回对象字面量)。很多现代代码库(包括 React 生态)更偏工厂函数,因为它不引入 this 与原型链的心智负担。

Object.create(null) 有什么用?

造一个没有原型的纯字典:① 不用担心 toString、constructor 这些继承属性干扰判断(if (obj[key]) 不会被误命中);② 避免原型污染攻击影响到 Object.prototype;③ 微小的性能优势。代价是它没有 hasOwnProperty、toString 等方法,需要 Object.hasOwn 这类静态方法。

为什么推荐 structuredClone 而不是 JSON.parse(JSON.stringify(x))?

因为 JSON 方案有六个丢失点(函数、undefined、Symbol 键、BigInt、Map/Set/Date 类型、循环引用)。structuredClone 用结构化克隆算法,能保留 Date/Map/Set/RegExp/ArrayBuffer 等类型并支持循环引用。它的限制是不能克隆函数(抛 DataCloneError)与 DOM 节点,且需要 Node 17+ 或现代浏览器。

原型链太长会影响性能吗?

会。属性查找要沿链逐级尝试,链越长越慢;更关键的是引擎的内联缓存(Inline Cache)会失效——同一个属性访问如果原型各不相同,JIT 无法生成快速路径。实践建议:原型链控制在 2~3 层(如"业务类 → 基类 → Object"),热点代码里避免频繁读写深层继承属性。


相关笔记

  • JavaScript-01-基础语法与类型 —— typeof 的怪癖、原始类型与引用语义的差别
  • JavaScript-02-函数与作用域 —— this 的绑定规则、new 绑定与类的强制严格模式
  • JavaScript-07-ES6新特性 —— 解构、展开运算符、Symbol、Proxy 与 Reflect
  • JavaScript-05-DOM与事件 —— DOM 节点也都是对象,事件对象与原型链的关系
  • JavaScript-06-模块化与工程化 —— 模块作用域与原型污染防护
  • 编程语言对比 —— 与 Python / C# 的类与对象模型对照
  • 数据结构-哈希表 —— 对象作为"字典"时的底层哈希实现与复杂度
  • 算法-复杂度分析 —— 本篇 、 记号的定义

参考来源