把方法定义在构造函数的 prototype 上可实现复用,所有实例共享同一份方法,节省内存且符合原型机制;class 语法糖本质相同;call/apply 复用属性初始化;object.create 支持纯原型委托复用。

构造函数本身负责创建对象实例并初始化属性,但若把方法直接写在构造函数内部,每次 new 都会重复生成一份新函数,浪费内存。真正实现代码复用的关键,在于把方法定义在构造函数的 prototype 上,让所有实例共享同一份方法。
把方法挂到 prototype 上
这是最基础也最有效的复用方式。每个构造函数都有一个 prototype 属性,它是一个对象,所有通过该构造函数创建的实例,都会通过隐式原型链(__proto__)指向它。
- 方法只定义一次,所有实例都能调用,且
===比较结果为true - 避免每次实例化都新建函数,节省内存
- 符合 JavaScript 原型机制的设计本意
示例:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
return `Hi, I'm ${this.name}`;
};
const a = new Person('Alice', 30);
const b = new Person('Bob', 25);
console.log(a.sayHello === b.sayHello); // true
用 class 语法糖更清晰地组织
ES6 的 class 是构造函数 + 原型操作的语法封装,写法更直观,但底层仍是原型复用。
- 类中定义的实例方法自动添加到
ClassName.prototype - 静态方法挂载在类本身,不参与实例复用,适合工具类逻辑
- 可读性高,团队协作时更易理解意图
示例:
class Animal {
constructor(name) { this.name = name; }
move() { return `${this.name} is moving`; } // → Animal.prototype.move
static createDefault() { return new Animal('unknown'); } // → Animal.createDefault
}
const cat = new Animal('Miao');
const dog = new Animal('Wang');
console.log(cat.move === dog.move); // true
DMap GL地图JSAPI(dmapgl)开发指南。用于编写、审查、调试 DMap 地图 API 代码,涵盖地图初始化、覆盖物渲染、图层管理、事件处理、控件交互等任务。当用户提及 dmap、dmapgl、jsapi‑gl 或相关地图开发需求时自动触发。
结合 call/apply 实现属性复用(模拟继承)
当多个构造函数有共用字段(如 name、id),可用 call 在子构造函数中复用父构造函数的初始化逻辑。
- 避免在子构造函数里重复写
this.name = name这类赋值 - 配合 prototype 链,实现属性 + 方法的双重复用
- 是传统“类式继承”的常用起点
示例:
function User(name, email) {
this.name = name;
this.email = email;
}
User.prototype.getInfo = function() {
return `${this.name} `;
};
function Admin(name, email, level) {
User.call(this, name, email); // 复用初始化
this.level = level;
}
Admin.prototype = Object.create(User.prototype); // 复用方法
Admin.prototype.constructor = Admin;
const admin = new Admin('Tom', 't@x.com', 'super');
console.log(admin.getInfo()); // Tom
用 Object.create 纯原型委托复用
不涉及构造函数时,也可直接以某个对象为原型创建新对象,适合配置对象、插件扩展等轻量场景。
- 跳过 new 和 this 绑定,更灵活
- 复用的是整个原型对象(包括已有属性和方法)
- 常用于默认配置合并、主题对象继承等
示例:
const defaults = {
timeout: 5000,
retries: 3,
log() { console.log('default log'); }
};
const customConfig = Object.create(defaults);
customConfig.timeout = 8000;
customConfig.log(); // default log










