应将方法定义在构造函数的 prototype 上,以实现所有实例共享同一函数对象、节省内存且保证方法相等性;class 语法是其语法糖,方法自动挂载到原型,但需避免在 prototype 上初始化引用类型。

在 JavaScript 中,用原型对象管理共享行为的核心是把方法定义在构造函数的 prototype 上,让所有实例共用同一份方法,节省内存、保持行为一致。
为什么要把方法放 prototype 上?
如果在构造函数内部用 this.xxx = function() {...} 定义方法,每次创建新实例都会生成一份新函数,既浪费内存,又导致 obj1.method === obj2.method 为 false。而写在 prototype 上的方法,所有实例通过原型链访问同一个函数对象。
基本写法:构造函数 + prototype
以创建“学生”为例:
function Student(name, grade) {
this.name = name;
this.grade = grade;
}
// 共享方法写在 prototype 上
Student.prototype.sayHello = function() {
return `你好,我是${this.name}`;
};
Student.prototype.getLevel = function() {
return this.grade >= 90 ? '优秀' : '良好';
};
const s1 = new Student('小明', 95);
const s2 = new Student('小红', 87);
console.log(s1.sayHello()); // 你好,我是小明
console.log(s2.getLevel()); // 良好
console.log(s1.sayHello === s2.sayHello); // true ✅
现代替代方案:class 语法(本质仍是原型)
class 是语法糖,底层仍操作原型。方法默认添加到 ClassName.prototype:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
立即学习“Java免费学习笔记(深入)”;
class Student {
constructor(name, grade) {
this.name = name;
this.grade = grade;
}
// 这些方法自动挂到 Student.prototype
sayHello() {
return `你好,我是${this.name}`;
}
getLevel() {
return this.grade >= 90 ? '优秀' : '良好';
}
}
效果和手动写 prototype 完全一致,可读性更好,推荐日常使用。
注意点:不要在 prototype 上放引用类型初始值
避免这样写:
// ❌ 危险!所有实例共享同一个数组
Student.prototype.hobbies = [];
// ✅ 正确:在 constructor 里初始化
function Student(name) {
this.name = name;
this.hobbies = []; // 每个实例独立
}
因为 prototype 是共享的,若放对象、数组等引用类型,修改会互相影响。

















