JavaScript原型继承通过[[Prototype]]链实现对象复用,核心方式包括Object.create()、构造函数prototype、手动设置原型链及ES6 class语法糖,均基于属性查找机制向上委托至null。

JavaScript 中原型继承实现对象复用,核心是让一个对象直接“链接”到另一个对象,从而共享其属性和方法,避免重复定义。它不依赖类,而是靠 [[Prototype]] 链天然支持属性查找——查不到就往上找,直到 null。
用 Object.create() 快速复用已有对象
这是最简洁、语义最清晰的方式:新对象的 __proto__ 直接指向要复用的对象。
-
语法简单:
const child = Object.create(parent); - 复用完整:child 能访问 parent 的所有自有属性和原型上的方法
- 无构造函数干扰:不执行父对象初始化逻辑,适合纯数据/行为模板场景
例如:
const animal = { eats: true, walk() { console.log("walking"); } };<br>
const rabbit = Object.create(animal);<br>
console.log(rabbit.eats); // true<br>
rabbit.walk(); // "walking"
通过构造函数原型链复用方法
当需要多个实例共用同一套方法时,把方法挂到构造函数的 prototype 上,实例自动继承。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 构造函数只管初始化自有属性(如 name、id)
- 所有实例共享 prototype 上的方法,节省内存
- 修改 prototype 会影响所有已有和未来实例
例如:
function Person(name) { this.name = name; }<br>
Person.prototype.say = function() { return `Hi, I'm ${this.name}`; };<br>
const a = new Person("Alice");<br>
const b = new Person("Bob");<br>
console.log(a.say === b.say); // true —— 同一个函数,复用成功
手动设置原型链实现多层复用
适用于构建层级结构(比如 Animal → Dog → Bulldog),每层复用上一层的能力。
立即学习“Java免费学习笔记(深入)”;
- 子构造函数的 prototype 设为父构造函数的实例
- 必须手动修复 constructor,否则 new 出来的实例 constructor 指向错误
- 注意引用类型属性会被所有实例共享(如数组、对象)
例如:
function Animal() {}<br>
Animal.prototype.eat = function() { console.log("eating"); };<br>
function Dog() {}<br>
Dog.prototype = new Animal(); // 复用 Animal 的能力<br>
Dog.prototype.constructor = Dog; // 修复 constructor<br>
Dog.prototype.bark = function() { console.log("woof"); };
ES6 class 是原型继承的语法糖
class 和 extends 看起来像传统类,但底层仍是原型链:子类 prototype 的 [[Prototype]] 指向父类 prototype。
- 方法自动挂到类的 prototype 上
super()等价于Parent.call(this, ...),负责初始化 this 上的自有属性- 静态方法挂在类本身,不参与原型链查找
例如:
class Animal { constructor(name) { this.name = name; }<br>
eat() { console.log(`${this.name} is eating`); } }<br>
class Dog extends Animal { bark() { console.log("Woof!"); } }<br>
const d = new Dog("Leo");<br>
d.eat(); // 复用 Animal.prototype.eat

















