Skip to content

JavaScript 面向对象与 class

JS 的面向对象和 Java/Python 长得不像:没有类声明(曾经)、继承走原型链、this 运行时绑定。ES2015 有了 class 语法,写法现代了,但底层的原型机制没变——不理解原型链,class 的 extends、super 也只是背语法。这篇从 new 讲到原型链再到 class,最后落到实战。

一、面向对象三件事

概念JS 里的体现
封装对象包数据和行为;私有成员用 #field 或闭包
继承原型链(extends 的底层)、混入(mixin)
多态同一方法不同对象有不同行为(依赖 this 和原型覆盖)

JS 早期没有 class 关键字,用"构造函数 + prototype"模拟面向对象;现在直接用 class,但构造函数和原型的知识依然是排查问题的基础。

二、实例对象与 new 命令

2.1 new 的四步流程

js
function User(name, age) {
  // 1. 新建空对象(内部完成)
  // 2. 空对象的原型指向 User.prototype(内部完成)
  this.name = name;          // 3. 用这个对象执行构造函数,this 指向它
  this.age = age;
  // 4. return this(内部完成)——除非显式 return 一个对象
}

const u = new User('甲', 18);
u.name;                      // '甲'
u instanceof User;           // true

手写一个 new,机制一目了然:

js
function myNew(constructor, ...args) {
  const obj = Object.create(constructor.prototype);   // 原型挂接
  const result = constructor.apply(obj, args);        // 执行,this = obj
  return result instanceof Object ? result : obj;     // 显式返回对象则用它
}

构造函数的返回值规则:return 一个对象 → new 的结果是那个对象;return 原始值 → 被忽略,照常返回 this。利用这个可以写"可重用的构造器",但属于黑魔法,知道就行。

2.2 忘写 new 的后果

js
function User(name) {
  this.name = name;
}
const bad = User('乙');      // 没有 new!
// 浏览器非严格:this 是 window,bad 是 undefined,window.name = '乙'
// 严格模式/模块:this 是 undefined,直接 TypeError: Cannot set properties of undefined

两种防御:

js
// 1. class 强制 new(class 不能不用 new 调用)
class User2 { constructor(name) { this.name = name; } }
User2('x');   // TypeError: Class constructor cannot be invoked without 'new'

// 2. 老构造函数的兼容写法
function User(name) {
  if (!(this instanceof User)) return new User(name);
  this.name = name;
}

2.3 箭头函数不能 new

js
const F = () => {};
new F();   // TypeError: F is not a constructor

class、函数声明/表达式可以 new,箭头函数、方法简写、async function、生成器不行(后两者是规范明确禁止,行为是抛 TypeError)。

三、this 关键字(OOP 视角)

函数篇讲过 this 的四条绑定规则,这里补 OOP 场景的三个要点:

js
class Counter {
  count = 0;
  // 类字段是实例属性,在构造时按定义顺序赋值
  inc = () => { this.count++; };     // 箭头函数字段:this 永远绑实例

  normalInc() { this.count++; }      // 普通方法:this 看调用
}

const c = new Counter();
const { normalInc } = c;
normalInc();          // TypeError——this 是 undefined(class 方法默认严格)
c.normalInc();        // OK
const inc = c.inc;
inc();                // OK——箭头字段绑死了 this

事件回调、定时器里用类方法的标准解法:

js
class SearchBox {
  constructor(input) {
    this.input = input;
    // 方案 1:bind(构造时一次)
    this.handle = this.handle.bind(this);
    input.addEventListener('input', this.handle);
    // 方案 2:箭头字段(推荐,见上)
  }
  handle(e) { this.search(e.target.value); }
  search(v) { /* ... */ }
}

四、prototype 与原型链

4.1 每时每刻都在发生的三件事

js
function Animal(name) { this.name = name; }
Animal.prototype.speak = function () { return `${this.name} makes a sound`; };

const dog = new Animal('狗');

// 1. 每个函数都有 prototype 属性(普通对象)
Animal.prototype;          // { speak: fn, constructor: Animal }

// 2. 每个实例都有 __proto__(非标准但通用),指向构造函数的 prototype
dog.__proto__ === Animal.prototype;         // true
Object.getPrototypeOf(dog) === Animal.prototype;  // true(正规 API)

// 3. 原型链顶端是 Object.prototype,再往上是 null
Animal.prototype.__proto__ === Object.prototype;   // true
Object.prototype.__proto__;                        // null——链到这里终止

4.2 属性查找沿链向上

js
dog.speak();               // '狗 makes a sound'
// 查找过程:dog 自己没有 speak → 找原型 Animal.prototype 找到 → 调用,this 是 dog

dog.toString();            // '[object Object]'
// dog → Animal.prototype → Object.prototype.toString——原型链上找到的

dog.hasOwnProperty('name');    // true(自身属性)
dog.hasOwnProperty('speak');   // false(原型上的)
'speak' in dog;                // true(in 含原型链)

4.3 原型方法共享,实例属性独立

js
const a = new Animal('甲');
const b = new Animal('乙');
a.speak === b.speak;        // true——同一个函数,存在原型上,所有实例共享
a.name === b.name;          // false——name 是构造时挂到实例自己的

**方法挂原型(省内存、可覆盖)、状态放实例(各管各)**是基本法。

4.4 原型链继承

js
function Dog(name) {
  Animal.call(this, name);      // 借父构造函数初始化实例属性
}
Dog.prototype = Object.create(Animal.prototype);   // 关键:挂到父原型,不是 Animal.prototype 本身
Dog.prototype.constructor = Dog;                   // 修正 constructor 指向
Dog.prototype.bark = function () { return '汪'; };

const d = new Dog('阿黄');
d.name;                 // '阿黄'(Animal.call 拷过来的)
d.speak();              // '阿黄 makes a sound'(沿链找到 Animal.prototype 的方法)
d.bark();               // '汪'
d instanceof Animal;    // true——原型链上有 Animal.prototype

这套"五件套"(call 继承属性、Object.create 挂原型、修 constructor、加子类方法)就是 class extends 编译后的样子。直接操作原型链的代码现在很少写,但读老代码、理解继承机制必须懂。

Dog.prototype = Animal.prototype 是大坑:子类改原型会污染父类,因为两边是同一个对象。必须 Object.create(Animal.prototype)。

五、class 语法

js
class Animal {
  // 静态属性/方法:挂在类上,不挂实例
  static kingdom = '动物界';
  static create(name) { return new Animal(name); }

  // 私有字段:类外部真的访问不到(# 语法,Chrome 74+)
  #secret = '私有数据';
  #age = 0;                 // 由下面 age 访问器控制读写
  #privMethod() { return this.#secret; }

  // 实例字段:每个实例一份
  name;

  // 构造函数
  constructor(name) {
    this.name = name;
  }

  // 方法:挂原型,所有实例共享
  speak() { return `${this.name} 叫了一声`; }

  // getter/setter:私有字段 + 访问器控制
  get age() { return this.#age; }
  set age(v) { if (v < 0) throw new RangeError('年龄不能为负'); this.#age = v; }
  get info() { return `${this.name}(${this.age})`; }

  // 静态块(ES2022)
  static {
    console.log('类定义时执行一次');
  }
}

要点:

  1. 类不会提升(和函数声明不同),先定义后使用
  2. 类方法默认严格模式,方法里的 this 丢失时报 TypeError 而不是静默 window
  3. 字段 #age 私有、name 公开,混用时的 setter 注意自己引用私有字段,别递归
  4. 字段初始化在构造函数体之前按声明顺序执行

5.1 继承

js
class Dog extends Animal {
  #tricks = [];

  constructor(name, breed) {
    super(name);              // 必须调!调父构造,之后才能用 this
    this.breed = breed;
  }

  speak() {
    const parent = super.speak();   // 调父类同名方法
    return `${parent}(汪!)`;
  }

  learn(trick) { this.#tricks.push(trick); return this; }   // 链式
}

const d = new Dog('阿黄', '柴犬');
d.name;                    // '阿黄'
d.speak();                 // '阿黄 叫了一声(汪!)'
d.kingdom;                 // undefined——静态属性不继承到实例
Dog.kingdom;               // '动物界'——静态属性继承自父类
d instanceof Animal;       // true

// 常见错误:constructor 里 this 之前不调 super
// class B extends A { constructor() { this.x = 1; super(); } }   // ReferenceError

super(name) 之前不能碰 this——父构造还没跑,实例没初始化。ES2022 字段初始化后这条更严格,直接用 this 就炸。

5.2 静态方法与静态属性

js
class Circle {
  static PI = 3.14159;
  static fromDiameter(d) { return new Circle(d / 2); }   // 工厂:替代构造重载
  static isValid(r) { return r > 0; }
  #r;
  constructor(r) { this.#r = r; }
  get area() { return Circle.PI * this.#r ** 2; }
}

Circle.PI;                        // 3.14159
Circle.fromDiameter(10).area;     // 78.5...
Circle.isValid(-1);               // false

静态方法是"命名空间下的工具函数",不依赖实例状态(Array.from、Object.keys、Number.isNaN 全是这个模式)。静态方法里的 this 是类本身(Circle),不是实例。

5.3 私有成员的三种实现对比

方式真私有语法场景
#field是(语言级)新现代项目首选
_field 约定否(只是风格)下划线开头老代码、库的公共 API
闭包工厂是return { get }不用 class 的模块
js
// 闭包私有(不用 class 也行)
function createTemperature(celsius) {
  let c = celsius;                    // 闭包变量,外部不可见
  return {
    get celsius() { return c; },
    set celsius(v) { c = v; },
    get fahrenheit() { return c * 9 / 5 + 32; },
  };
}

5.4 instanceof 与类型判断

js
d instanceof Dog;          // true
d instanceof Animal;       // true——沿原型链找 Animal.prototype
d instanceof Object;       // true——链顶

// instanceof 的局限:跨 realm(iframe)失效、Symbol.hasInstance 可被篡改
// 更稳的类判断:
Object.getPrototypeOf(d) === Dog.prototype;      // 精确
d.constructor === Dog;                            // 可被改写,慎用

5.5 实战:自定义错误类型

业务里最值得用 class 的地方——带错误码、带上下文的错误:

js
class AppError extends Error {
  constructor(message, code, context = {}) {
    super(message);
    this.name = 'AppError';        // 修正 name(子类默认是 'Error')
    this.code = code;
    this.context = context;
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, AppError);   // 干净堆栈(V8)
    }
  }
}

class HttpError extends AppError {
  constructor(message, status) {
    super(message, `HTTP_${status}`, { status });
    this.status = status;
  }
}

throw new HttpError('用户不存在', 404);
// err.code === 'HTTP_404'、err.status === 404、err instanceof Error === true

细节:extends Error 后必须调 super(message),stack 才有内容;name 不手动设的话是 'Error',错误日志里分不清类型。更多错误处理见错误处理与调试篇。

六、混入(Mixin):JS 的"多继承"

JS 单继承(一个 extends),需要组合能力时用 mixin:

js
// 可序列化混入:给类加 toJSON 能力
const Serializable = Base => class extends Base {
  toJSON() { return { ...this }; }
};

// 可克隆混入
const Cloneable = Base => class extends Base {
  clone() { return Object.assign(Object.create(Object.getPrototypeOf(this)), this); }
};

class User extends Serializable(Cloneable(Object)) {
  constructor(name) { super(); this.name = name; }
}

const u = new User('甲');
u.clone().name;        // '甲'
JSON.stringify(u);     // '{"name":"甲"}'

React 生态里 mixin 已被否定,但普通 TS/JS 库里仍常见。组合优于继承——能把功能写成独立函数就别急着造继承层级。

七、常见坑速查

写法结果原因
class 先调用后定义ReferenceError类不提升
extends 的 constructor 先写 this 再 superReferenceErrorthis 未初始化
Dog.prototype = Animal.prototype父类被污染共享同一个原型对象
箭头函数当构造器 newTypeError无 prototype、不能 new
静态方法里 this.xxx 找实例字段undefined静态 this 是类
obj.constructor === Array 判数组可能误判constructor 可改,用 Array.isArray
子类方法同名想调父类Parent.prototype.method.call(this)class 里用 super.method()

相关阅读

CTO Plus技术栈 Version 1.0.20261024-12