通过修改构造函数的 prototype 属性来实现方法复用。具体做法是将需要共享的方法定义在构造函数原型对象上,这样所有实例都会继承这些方法,从而避免在每个实例中重复创建函数副本。

如何为自定义类添加共享方法
将方法直接赋值给 Constructor.prototype 即可。例如定义一个 User 类,把 greet 方法挂在原型上,实例调用时会自动查找并执行同一份函数逻辑。

function User(name) {
this.name = name;
}
User.prototype.greet = function() {
return 'Hello, ' + this.name;
};
const u1 = new User('Alice');
const u2 = new User('Bob');
console.log(u1.greet()); // Hello, Alice
console.log(u2.greet()); // Hello, Bob
console.log(u1.greet === u2.greet); // true运行上述代码后,u1.greet 和 u2.greet 指向同一个函数引用,内存中只存在一份 greet 方法的副本。
立即学习“Java免费学习笔记(深入)”;
使用 Object.assign 批量挂载原型方法
当原型方法较多时,可以使用 Object.assign 一次性将多个方法复制到原型对象上。这种方式保持与手动逐个赋值相同的效果,但代码更紧凑。

function Product(id, price) {
this.id = id;
this.price = price;
}
Object.assign(Product.prototype, {
formatPrice() {
return '$' + this.price.toFixed(2);
},
isExpensive(threshold) {
return this.price > threshold;
}
});
const p = new Product(1, 19.5);
console.log(p.formatPrice()); // $19.50
console.log(p.isExpensive(10)); // true执行结果验证了 formatPrice 和 isExpensive 均能正常访问实例属性,且两个实例共享这些方法。
原型链查找失败时会发生什么
如果实例上没有对应方法,JavaScript 引擎会沿着原型链向上查找。若最终未找到,调用该属性会得到 undefined,尝试调用它会抛出 TypeError。例如删除 User.prototype.greet 后,u1.greet() 将报错。


















